gpt4 book ai didi

python - 当我运行 find_all 时,BeautifulSoup 添加内容

转载 作者:太空宇宙 更新时间:2023-11-03 17:41:02 29 4
gpt4 key购买 nike

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

网址是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))

这仅返回有机列表部分中的内容。有 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

这会返回原始 30 个列表以及来自 (aside id="main-aside") 的另外 10 个列表,这些列表未包含在变量“organic”中。

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

最佳答案

使用 "xml" 您可以通过 soup.find("div", {"class": "search 找到 41 class="info"> -results Organic"}) 因此,使用 find_all 返回 41 并不奇怪。您将获得返回的其他元素,通过查看有机返回即可轻松看到这些元素,即 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

您得到了正确的结果。

关于python - 当我运行 find_all 时,BeautifulSoup 添加内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30548727/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com