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

标签 python python-2.7 web-scraping beautifulsoup

我正在尝试从电视节目中抓取一些脚本。我可以使用 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/

相关文章:

php - 如何使用 Goutte 在 laravel 5.2 中进行抓取?

javascript - 如何为数组中的每个对象添加新字段?

python - 如何在 Git Bash 上更新 python?

python - 如何实现gtksourceview2.CompletionProvider?

python - 查找存储在数据框单元格中的列表

multithreading - selenium 线程可以安全地使用 Python 进行抓取吗?

python - 重新定义python内置函数

python - 使用 pyodbc 导致错误 : Data source name not found and no default driver specified

python - Django 单元测试随机失败

python - xpath不能只选择一个html标签