如何使用Python中的Beautiful Soup在HTML页面中查找特定单词?

5
我想要通过Beautiful Soup在HTML文本中查找一个特定单词出现的次数。我尝试使用findAll函数,但它只能找到特定标签内的单词,例如soup.body.findAll只会在标签内查找特定单词,而我想要搜索所有标签内的该单词。此外,一旦找到该单词,我需要创建一个列表,其中包含该单词前后的单词。请问是否有人能够帮助我?谢谢。

可能是重复的问题:使用BeautifulSoup搜索HTML字符串 - Ritave
不,这不是重复的,我已经检查过了。 - Kanika Singh
1个回答

8
根据最新的BeautifulSoup 4 api,您可以使用“recursive”关键字在整个树中查找文本。然后,您将获得字符串,可以对其进行操作并分离单词。
这是一个完整的示例:
import bs4
import re

data = '''
<html>
<body>
<div>today is a sunny day</div>
<div>I love when it's sunny outside</div>
Call me sunny
<div>sunny is a cool word sunny</div>
</body>
</html>
'''

searched_word = 'sunny'

soup = bs4.BeautifulSoup(data, 'html.parser')
results = soup.body.find_all(string=re.compile('.*{0}.*'.format(searched_word)), recursive=True)

print 'Found the word "{0}" {1} times\n'.format(searched_word, len(results))

for content in results:
    words = content.split()
    for index, word in enumerate(words):
        # If the content contains the search word twice or more this will fire for each occurence
        if word == searched_word:
            print 'Whole content: "{0}"'.format(content)
            before = None
            after = None
            # Check if it's a first word
            if index != 0:
                before = words[index-1]
            # Check if it's a last word
            if index != len(words)-1:
                after = words[index+1]
            print '\tWord before: "{0}", word after: "{1}"'.format(before, after)

它输出:
Found the word "sunny" 4 times

Whole content: "today is a sunny day"
    Word before: "a", word after: "day"
Whole content: "I love when it's sunny outside"
    Word before: "it's", word after: "outside"
Whole content: "
Call me sunny
"
    Word before: "me", word after: "None"
Whole content: "sunny is a cool word sunny"
    Word before: "None", word after: "is"
Whole content: "sunny is a cool word sunny"
    Word before: "word", word after: "None"

也可以在这里查看字符串关键字参考资料


results = soup.body.find_all(string=searched_word, recursive=True) NameError: 名称 'True' 未定义 - Kanika Singh
我已经下载了http://www.crummy.com/software/BeautifulSoup/bs4/download/ 版本为4.3。 - Kanika Singh
我更新了答案,并提供了完整的、可工作的示例,请再次检查。 - Ritave
似乎string关键字是在4.4版本中添加的,因此请使用该关键字或将soup.body.find_all(string=...)更改为soup.body.find_all(text=...)(4.3及之前版本的不同关键字)。 - Ritave
这个似乎在规模上变得疯狂起来...我正在使用一个SoupObject,并尝试找到所有在aria-labelledby之后或者包含类似"aria-labelledby="listing_"的字符串的东西。你知道我应该如何调整这个或者有其他方法来找到我想要的东西吗?这是一个包含我的函数的示例页面:https://gist.github.com/gumdropsteve/8268ddb157a8b987265d6b29a86d6dda - undefined
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接