【问题标题】:Scraping text containing certain caracters and names in Python?在 Python 中抓取包含某些字符和名称的文本?
【发布时间】: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


【解决方案1】:

首先,您不需要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 '“"-' 部分检查“"- 是否包含剥离文本值的第一个字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    相关资源
    最近更新 更多