gpt4 book ai didi

python - 使用 BeautifulSoup 查找特定标签

转载 作者:太空宇宙 更新时间:2023-11-03 16:25:04 25 4
gpt4 key购买 nike

这是我正在解析的网站:http://uniapple.net/usaddress/address.php?address1=501+10th+ave&address2=&city=nyc&state=ny&zipcode=10036&country=US

我希望能够找到第 39 行 td 标签之间的单词。该行告诉我该地址是住宅地址还是商业地址,这正是我的脚本所需要的。

这是我所拥有的,但我收到此错误:

AttributeError: 'NoneType' object has no attribute 'find_next'

我使用的代码是:

from bs4 import BeautifulSoup
import urllib


page = "http://uniapple.net/usaddress/address.php?address1=501+10th+ave&address2=&city=nyc&state=ny&zipcode=10036&country=US"
z = urllib.urlopen(page).read()
thesoup = BeautifulSoup(z, "html.parser")
comres = (thesoup.find("th",text=" Residential or ").find_next("td").text)
print(str(comres))

最佳答案

text 参数在这种特殊情况下不起作用。这与.string property的方式有关。计算一个元素的值。相反,我会使用 search function您实际上可以在其中调用 get_text() 并检查元素的完整“文本”(包括子节点):

label = thesoup.find(lambda tag: tag and tag.name == "th" and \
"Residential" in tag.get_text())
comres = label.find_next("td").get_text()
print(str(comres))

打印商业

我们可以更进一步,创建一个可重用函数来通过标签获取值:

soup = BeautifulSoup(z, "html.parser")

def get_value_by_label(soup, label):
label = soup.find(lambda tag: tag and tag.name == "th" and label in tag.get_text())
return label.find_next("td").get_text(strip=True)


print(get_value_by_label(soup, "Residential"))
print(get_value_by_label(soup, "City"))

打印:

Commercial
NYC

关于python - 使用 BeautifulSoup 查找特定标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38057756/

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