Python遍历HTML标记并使用IF

2024-05-14 23:32:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python从网页中提取数据。该网页有一个重复出现的htmldiv标记class=“result”,其中包含其他数据(如位置、组织等)。我可以使用beautiful soup成功地遍历html,但是当我添加一个条件,比如如果某个单词(例如,NHS)存在于该段中,它不会返回任何内容——尽管我知道某些片段包含它。代码如下:

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

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

希望我的问题有意义。。。在


Tags: 数据in标记网页htmlresultdetails条件
1条回答
网友
1楼 · 发布于 2024-05-14 23:32:32

findAll返回标记列表,而不是字符串。或者把它们转换成字符串?在

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

您正在标记中查找字符串。最好在字符串中寻找一个字符串。。。在

^{pr2}$

相关问题 更多 >

    热门问题