Python - 遍历 HTML 标签并使用 IF

Python - Looping through HTML Tags and using IF

我正在使用 python 从网页中提取数据。该网页有一个重复出现的 html div 标签和 class = "result",其中包含其他数据(例如位置、组织等...)。我能够使用漂亮的汤成功地遍历 html 但是当我添加一个条件时,例如如果某个词('NHS' 例如)存在于段中它不 return任何东西——尽管我知道某些片段包含它。这是代码:

soup = BeautifulSoup(content)
details = soup.findAll('div', {'class': 'result'})

for detail in details:
    if 'NHS' in detail:
        print detail

希望我的问题有道理...

findAll returns 标签列表,不是字符串。也许将它们转换为字符串?

s = "<p>golly</p><p>NHS</p><p>foo</p>"
soup = BeautifulSoup(s)
details = soup.findAll('p')
type(details[0])    # prints: <class 'BeautifulSoup.Tag'>

您正在标签中查找字符串。最好在字符串中寻找字符串...

for detail in details:
    if 'NHS' in str(detail):
        print detail