使用 BeautifulSoup 查找特定标签

Finding specific tag using BeautifulSoup

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

你所缺少的只是一点家务:

ths = thesoup.find_all("th")
for th in ths:
    if 'Residential or' in th.text:
        comres = th.find_next("td").text
        print(str(comres))
        >> Commercial

text 参数在这种特殊情况下不起作用。这与 .string property of an element is calculated. Instead, I would use a search function 如何实际调用 get_text() 并检查包含子节点的元素的完整 "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))

打印 Commercial.

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

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

您需要使用正则表达式作为文本字段,例如 re.compile('Residential or'),而不是字符串。

这对我有用。我不得不遍历提供的结果,但如果你只希望每页有一个结果,你可以将 find 换成 find_all:

for r in thesoup.find_all(text=re.compile('Residential or')):
    r.find_next('td').text