我正在尝试从电视节目中抓取一些脚本。我可以使用 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'))
关于python - BeautifulSoup - 仅当找到特定字符串时才在标签内获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40221191/