在Python中抓取包含某些字符和名称的文本?



我对python相当陌生,并且正在做一个项目,我需要一堆文章中某些人的所有引用。

对于这个问题,我使用这篇文章作为示例:https://www.theguardian.com/us-news/2021/oct/17/jeffrey-clark-scrutiny-trump-election-subversion-scheme

现在,使用Lambda,我可以使用以下代码抓取包含我正在查找的人名的文本:

import requests
from bs4 import BeautifulSoup
url = 'https://www.theguardian.com/us-news/2021/oct/17/jeffrey-clark-scrutiny-trump-election-subversion-scheme'
response = requests.get(url)
data=response.text
soup=BeautifulSoup(data,'html.parser')
tags=soup.find_all('p')
words = ["Michael Bromwich"]
for tag in tags:
quotes=soup.find("p",{"class":"dcr-s23rjr"}, text=lambda text: text and any(x in text for x in words)).text
print(quotes)

…它返回包含"Michael bromwich"的文本块,在本例中,它实际上是文章中的引用。但是当抓取100篇以上的文章时,这是行不通的,因为其他文本块也可能包含指示的名称,但不包含引号。我只需要包含引号的文本字符串。

因此,我的问题:是否有可能在下列条件下打印所有HTML字符串:

文本以&quot字符开始(引号)OR -(连字符)AND包含名字"Michael bromwich";约翰·约翰逊;等。

谢谢!

首先,您不需要for tag in tags循环,您只需要根据您的条件使用soup.find_all

接下来,您可以检查没有任何正则表达式的引号或连字符:

quotes = [x.text for x in  soup.find_all("p",{"class":"dcr-s23rjr"}, text=lambda t: t and (t.startswith("“") or t.startswith('"') or t.startswith("-")) and any(x in t for x in words))]

(t.startswith("“") or t.startswith('"') or t.startswith("-"))部分将检查文本是否以,"-开头。

quotes = [x.text for x in  soup.find_all("p",{"class":"dcr-s23rjr"}, text=lambda t: t and t.strip()[0] in '“"-' and any(x in t for x in words))]

t.strip()[0] in '“"-'部分检查“"-是否包含剥离文本值的第一个字符。

最新更新