Python检索文章是否具有auth

2024-10-03 21:27:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个Python脚本来检索一篇文章是否有作者。你知道吗

我写了以下内容:

s = "https://www.nytimes.com/2017/08/18/us/politics/steve-bannon-trump-white-house.html?hp&action=click&pgtype=Homepage&clickSource=story-heading&module=a-lede-package-region&region=top-news&WT.nav=top-news"

def checkForAuthor():
    r = requests.get(s)
    return "By" in r.text

print(checkForAuthor())

问题是函数checkForAuthor返回true,即使没有作者,因为它搜索整个HTML内容来查找单词。 有没有更好的逻辑来寻找作者而不必搜索整个文档?例如在标题中搜索,这样我甚至不必搜索文章内容。我确实需要使这个一般,以便任何网站,我去搜索它会给我的结果。不知道外面有没有这样的东西。你知道吗


Tags: https脚本comtopwww文章作者region
2条回答

要解析html并查找所需的数据,应该使用BeautifulSoup库。你知道吗

在URL的html中,有一个带有作者的meta标记:

<meta content="By MAGGIE HABERMAN, MICHAEL D. SHEAR and GLENN THRUSH" name="byl"/>

因此,要检查是否有作者,您需要通过其名称(byl)找到它:

import requests
from bs4 import BeautifulSoup

s = "https://www.nytimes.com/2017/08/18/us/politics/steve-bannon-trump-white-house.html?hp&action=click&pgtype=Homepage&clickSource=story-heading&module=a-lede-package-region&region=top-news&WT.nav=top-news"

def checkForAuthor():
    soup = BeautifulSoup(requests.get(s).content, 'html.parser')
    meta = soup.find('meta', {'name': 'byl'})
    return meta is not None

实际上,您还可以通过meta["content"]获得作者名称

从网页中抓取数据的一个关键部分是查看网页的HTML源以正确地获取数据。在您提供的链接中,有以下几行包含作者信息。你知道吗

<meta name="author" content="Maggie Haberman, Michael D. Shear and Glenn Thrush" />
<meta name="byl" content="By MAGGIE HABERMAN, MICHAEL D. SHEAR and GLENN THRUSH" />
<meta property="article:author" content="https://www.nytimes.com/by/maggie-haberman" />
<meta property="article:author" content="https://www.nytimes.com/by/michael-d-shear" />
<meta property="article:author" content="https://www.nytimes.com/by/glenn-thrush" />

还有其他的,但这些应该会有所帮助。要解析这些标记,可以使用beautiful-soup。你知道吗

相关问题 更多 >