Skip to main content
 首页 » 编程设计

python之BeautifulSoup之仅当找到特定字符串时才在标签内获取文本

2025年04月02日23cloudgamer

我正在尝试从电视节目中抓取一些脚本。我可以使用 BeautifulSoup 和 Requests 根据需要获取文本。

import requests 
from bs4 import BeautifulSoup 
 
r = requests.get('http://www.example.com') 
s = BeautifulSoup(r.text, 'html.parser') 
 
for p in s.find_all('p'): 
    print p.text 

目前效果很好。但我只想要某个角色的那些段落。说他的名字是“stackoverflow”。文本将是这样的:

A: sdasd sd asda B: sdas 堆栈溢出:帮助?

所以我只想要 STACKOVERFLOW 所说的内容。不是其余的。

我试过了

s.find_all(text='STACKOVERFLOW') but I get nothing. 

这样做的正确方法是什么?将不胜感激正确方向的提示。

请您参考如下方法:

使部分文本匹配,或者:

s.find_all(text=lambda text: text and 'STACKOVERFLOW' in text) 

或者:

import re 
 
s.find_all(text=re.compile('STACKOVERFLOW'))