BeautifulSoup-仅在找到特定字符串的情况下,在标签内获取文本 [英] BeautifulSoup - Get Text within tag only if a certain string is found

查看:258
本文介绍了BeautifulSoup-仅在找到特定字符串的情况下,在标签内获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从电视节目中抓取一些脚本.我可以使用BeautifulSoup和Requests获取所需的文本.

I am trying to scrape some scripts from a TV-Show. I am able to get the text as I need it using BeautifulSoup and 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".文字是这样的:

This works great so far. But I want only those paragraphs from a certain character. Say his name is "stackoverflow". The text would be like this:

A:sdasd sd asda B:sdasds STACKOVERFLOW:帮助吗?

A: sdasd sd asda B: sdasds STACKOVERFLOW: Help?

所以我只想要STACKOVERFLOW所说的内容.剩下的就不行了.

So I only want the stuff that STACKOVERFLOW says. Not the rest.

我尝试过

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

什么是正确的方法?朝着正确方向的提示将不胜感激.

What would be the right way to do this? A hint in the right direction would be most appreciated.

推荐答案

使 partial 文本匹配,或者使用:

Make the partial text match, either with:

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

或者:

import re

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

这篇关于BeautifulSoup-仅在找到特定字符串的情况下,在标签内获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆