使用BeautifulSoup在html中搜索字符串

kac*_*ous 43 python beautifulsoup

我正在使用BeautifulSoup在特定页面上查找用户输入的字符串.例如,我想看看字符串'Python'是否位于页面上:http://python.org

当我使用: find_string = soup.body.findAll(text='Python') find_string返回[]

但是当我使用: find_string = soup.body.findAll(text=re.compile('Python'), limit=1) find_string [u'Python Jobs']按预期返回

这两个语句之间的区别是,当要搜索的单词有多个实例时,第二个语句会起作用

小智 52

以下行正在寻找确切的 NavigableString'Python':

>>> soup.body.findAll(text='Python')
[]
Run Code Online (Sandbox Code Playgroud)

请注意,找到以下NavigableString:

>>> soup.body.findAll(text='Python Jobs') 
[u'Python Jobs']
Run Code Online (Sandbox Code Playgroud)

请注意此行为:

>>> import re
>>> soup.body.findAll(text=re.compile('^Python$'))
[]
Run Code Online (Sandbox Code Playgroud)

所以你的正则表达式正在寻找"Python"的出现,而不是与NavigableString'Python'完全匹配.

  • 是否可以获取特定文本的父标记? (5认同)
  • @Samay `soup.find(text='Python Jobs').parent` — 来自文档:["Going up"](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#going-up ) (5认同)

jfs*_*jfs 23

text='Python' 搜索具有您提供的确切文本的元素:

import re
from BeautifulSoup import BeautifulSoup

html = """<p>exact text</p>
   <p>almost exact text</p>"""
soup = BeautifulSoup(html)
print soup(text='exact text')
print soup(text=re.compile('exact text'))
Run Code Online (Sandbox Code Playgroud)

产量

[u'exact text']
[u'exact text', u'almost exact text']
Run Code Online (Sandbox Code Playgroud)

"要查看字符串'Python'是否位于页面http://python.org上 ":

import urllib2
html = urllib2.urlopen('http://python.org').read()
print 'Python' in html # -> True
Run Code Online (Sandbox Code Playgroud)

如果你需要在字符串中找到子串的位置,你可以做html.find('Python').

  • @Timo 从[我链接的 StackOverflow 问题的接受答案](/sf/answers/326542261/) 复制代码。确保代码片段在您的环境中工作。开始将其更改为您的任务(一次一个简单的更改)。一旦它中断(当它做了一些意想不到的事情时),将其用作[提出新的 StackOverflow 问题的最小可重现代码示例](https://stackoverflow.com/help/minimal-reproducible-example) (2认同)

Men*_*elG 5

除了公认的答案。您可以使用 alambda代替regex

from bs4 import BeautifulSoup

html = """<p>test python</p>"""

soup = BeautifulSoup(html, "html.parser")

print(soup(text="python"))
print(soup(text=lambda t: "python" in t))
Run Code Online (Sandbox Code Playgroud)

输出:

[]
['test python']
Run Code Online (Sandbox Code Playgroud)