python - 使用 BeautifulSoup 查找特定标签

标签 python html beautifulsoup html-parsing

这是我正在解析的网站: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/

相关文章:

python - 同时运行多个python脚本实例

html - 将输入类型文本放在图像的中心

python - HTML逐行解析

python - 以编程方式将模块/函数集转换为 Python 类

python - 在python中通过windows cmd用记事本打开服务器上的文件

javascript - 仅在谷歌驱动器中使用谷歌表格作为数据库

python - Beautiful Soup Find() 返回 AttributeError

python beautifulsoup 只返回键 {} 而不是值

python - 字符串中的一个热点 - 获取唯一值列表中的索引

javascript - Highcharts:将值(value)最小的系列放在顶部