python - BeautifulSoup 无法使用 find_all() 提取项目

标签 python html regex beautifulsoup

我尝试使用 BeautfulSoup 从 HTML 中获取文本的位置,如下所示,这是我的 html:

<p><em>code of Drink<br></em>
Budweiser: 4BDB1CD96<br>
price: 10$</p>

带有代码:

soup = BeautifulSoup(html,'lxml')
result = re.escape('4BDB1CD96')
tag = soup.find(['li','div','p','em'],string=re.compile(result))

我无法提取标签,但我将 find_all() 更改为: 标签 = soup.find(string=re.compile(结果)) 然后我可以得到结果: 百威啤酒:4BDB1CD96 所以我想知道为什么以及如何获得像标签 fromat 中的结果

最佳答案

这里的问题是您的标签具有嵌套标签,并且您正在搜索的文本位于此类标签内(此处为p)。

因此,最简单的方法是在 .find() 中使用 lambda 来检查标签名称以及 .text 属性是否包含您的模式。在这里,您甚至不需要正则表达式:

>>> tag = soup.find(lambda t: t.name in ['li','div','p','em'] and '4BDB1CD96' in t.text)
>>> tag
<p><em>code of Drink<br/></em>
Budweiser: 4BDB1CD96<br/>
price: 10$</p>
>>> tag.string
>>> tag.text
'code of Drink\nBudweiser: 4BDB1CD96\nprice: 10$'

当然,您可以使用正则表达式进行更复杂的搜索:

r = re.compile('4BDB1CD96') # or whatever the pattern is
tag = soup.find(lambda t: t.name in ['li','div','p','em'] and r.search(t.text))

关于python - BeautifulSoup 无法使用 find_all() 提取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51319019/

相关文章:

python - 发现未记录程序的 IPC 接口(interface)?

python - 如何使用多处理实现发布/订阅模式?

javascript - 使用 KineticJS 的图表创建器

python - 名称错误 : name 'X' is not defined sklearn

python - 如果输出有字符,我需要运行 bash 命令;如果输出为空,我需要运行其他命令

javascript - 如何从 Javascript 创建 Bootstrap 弹出窗口?

php - 添加到不同表时删除一行

regex - Bash - killall -r 不匹配

javascript - 正则表达式查找字符串中的 URL

sql - 用于匹配 T-SQL 脚本中所有注释的正则表达式