【发布时间】:2021-12-05 11:02:48
【问题描述】:
我对 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 字符串:
文本以字符“(引号)或 -(连字符)开头 并且包含名称“Michael Bromwich”或“John Johnson”等。
谢谢!
【问题讨论】:
-
我认为你不需要正则表达式,
soup.find("p",{"class":"dcr-s23rjr"}, text=lambda t: t and (t.startswith("“") or t.startswith("-")) and any(x in t for x in words)).text应该这样做。引号总是卷曲的吗?还是您需要支持任何类型的引号?连字符也一样:你需要支持任何类型的破折号吗? -
这就是工作!谢谢你。但它并不总是大括号,不。如何区分 t.startswith(""") 中的直引号和其他两个引号?
-
查看我的答案,还有一种方法可以将此检查缩短为
t.strip()[0] in '“"-'。如果您需要添加其他引号,请将它们添加为t.strip()[0] in '''“"'‘-'''
标签: python regex lambda beautifulsoup quotes