BeautifulSoup 当我 运行 find_all 添加内容

BeautifulSoup adds content when I run find_all

我正在尝试从 yp.com 中抓取列表,并且在构建代码时,我能够隔离名称为 (div class="search-results organic") 的部分,但是当我 运行 find_all() 在该内容上,它 returns 在该部分之外列出。

URL是http://www.yellowpages.com/search?search_terms=septic&geo_location_terms=80521

这就是我 运行宁:

from bs4 import BeautifulSoup
import urllib
import re
import xml
import requests
from urlparse import urlparse

filename = "webspyorganictag.html"
term = "septic"
zipcode = "80521"
url = "http://www.yellowpages.com/search?search_terms="+ term +"&geo_location_terms="+ zipcode

with open(filename, "w") as myfile:
    myfile.write("Information from the organic<br>")

r = requests.get(url)
soup = BeautifulSoup(r.content, "xml")
organic = soup.find("div", {"class": "search-results organic"})

with open(filename, "a") as myfile:
    myfile.write(str(organic))

而这个 returns 只是有机列表部分中的内容。有 30 个列表。

然后,我添加:

listings = organic.find_all("div", {"class": "info"})
i = 1
with open(filename, "a") as myfile:
    for listing in listings:
        myfile.write("This is listing " + str(i) + "<br>")
        myfile.write(str(listing) + "<br>")
        i += 1

而这个 returns 原始的 30 个列表加上来自(除了 id="main-aside")的另外 10 个列表,它们不包含在变量 'organic' 中。

不应该调用 organic.find_all() 将范围限制为变量 'organic' 中的数据吗?

使用 "xml" 你会发现 41 class="info">soup.find("div", {"class": "search-results organic"}) 所以你得到 41 和 find_all 就不足为奇了。您正在返回其他元素,这可以通过查看有机 returns 即 href="/wray-co/mip/ritcheys-redi-mix-precast-inc-10367117?lid=1000575822573"href="/longmont-co/mip/rays-backhoe-service-6327932?lid=216924340" 以及十个特色中的所有其他列表轻松看出。

如果您查看 html 的第 41 行,您会写它还包含:

href="/wray-co/mip/ritcheys-redi-mix-precast-inc-10367117?lid=1000575822573" 这是最后一个特色列表。

问题出在解析器上,如果您将解析器更改为 "lxml":

soup = BeautifulSoup(r.content,"lxml")

organic = soup.find("div", {"class": "search-results organic"})

print(len(organic.find_all("h3",{"class":"info"})))
30

或使用html.parser

soup = BeautifulSoup(r.content,"html.parser") 

organic = soup.find("div", {"class": "search-results organic"})

print(len(organic.find_all("div",{"class":"info"})))
30

你得到了正确的结果。