python - 使用 BeautifulSoup 的 findAll 搜索 html 元素的 innerText 以获得与搜索属性相同的结果?

标签 python beautifulsoup

例如,如果我通过元素的属性(如 id)进行搜索:

soup.findAll('span',{'id':re.compile("^score_")})

我得到了匹配的整个 span 元素的列表(我喜欢)。

但是如果我尝试像这样通过 html 元素的 innerText 进行搜索:

soup.findAll('a',text = re.compile("discuss|comment")) 

我只返回匹配的元素的 innerText 部分,而不是像上面那样返回带有标签和属性的整个元素。

这是否可以在不找到匹配项然后获取它的父项的情况下进行?

谢谢。

最佳答案

您不会取回文本。您会得到一个带有文本的 NavigableString。该对象具有转到父级等的方法。

from BeautifulSoup import BeautifulSoup
import re

soup = BeautifulSoup('<html><p>foo</p></html>')

r = soup.findAll('p', text=re.compile('foo'))

print r[0].parent

打印

<p>foo</p>

关于python - 使用 BeautifulSoup 的 findAll 搜索 html 元素的 innerText 以获得与搜索属性相同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2580507/

相关文章:

python - Python 模块系统上令人困惑的语义

python - 使用python从给定的音频文件中检测静音索引

Python 3 : how to scrape research results from a website using CSFR?

python-3.x - 如何使用 selenium 线程进行网页抓取?

python - 优化 BeautifulSoup (Python) 代码

Python 通过 TCP 读取 modbus

python - Flask SQLAlchemy 的表(模型)继承

python - tf.keras.layers.pop() 不起作用,但 tf.keras._layers.pop() 起作用

python - 无法使用 Beautifulsoup 抓取日期/时间信息

python - 如何使用 Mechanize 从 Google 的搜索结果中获取图像