Python BeautifulSoup-仅当找到某个字符串时,才在标记中获取文本

Python BeautifulSoup-仅当找到某个字符串时,才在标记中获取文本,python,python-2.7,web-scraping,beautifulsoup,Python,Python 2.7,Web Scraping,Beautifulsoup,我正试图从一个电视节目中摘取一些剧本。我可以使用BeautifulSoup和请求获取我需要的文本 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 到目前为止,这很有效。但我只想要某个角色的那些段落

我正试图从一个电视节目中摘取一些剧本。我可以使用BeautifulSoup和请求获取我需要的文本

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:SDDA B:SDSDS 斯塔克:救命

所以我只想要STACKOVERFLOW说的东西。不是其他的

我试过了

s.find_all(text='STACKOVERFLOW') but I get nothing.
这样做的正确方式是什么?如果你能给我一个正确的提示,我将不胜感激

使部分文本匹配,可以是:

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


您可以将自定义函数传递到
find\u all
。此函数应接受一个参数(标记),并为满足条件的标记返回
True

def so_tags(tag):
    '''returns True if the tag has text and 'stackoverflow' is in the text'''
    return (tag.text and "STACKOVERFLOW" in tag.text)

soup.find_all(my_tags)
您还可以创建一个函数工厂,使其更具动态性

def user_paragraphs(user):
    '''returns a function'''
    def user_tags(tag):
        '''returns True for tags that have <user> in the text'''
        return (tag.text and user in tag.text)
    return user_tags

for user in user_list:
    user_posts = soup.find_all(user_paragraphs(user))
def user_段落(用户):
''返回一个函数''
def用户标签(标签):
''对于文本''中包含的标记返回True'
返回(tag.text和tag.text中的用户)
返回用户标签
对于用户列表中的用户:
user_posts=soup.find_all(user_段落(user))
def user_paragraphs(user):
    '''returns a function'''
    def user_tags(tag):
        '''returns True for tags that have <user> in the text'''
        return (tag.text and user in tag.text)
    return user_tags

for user in user_list:
    user_posts = soup.find_all(user_paragraphs(user))