【问题标题】:Scraping meta tags with BS4 or Newspaper3k in Python在 Python 中使用 BS4 或 Newspaper3k 抓取元标记
【发布时间】:2020-05-09 11:06:30
【问题描述】:

经过详尽的搜索和许多变化,我不知所措。我知道 BS4(我也试过 3)应该能够抓取元标记,但我似乎无法让它工作。有问题的元标记已关闭<properly />,所以不是这样。它们总是存在(即使我设置了一个以防万一),所以不是这样。我尝试过循环,我为同一件事尝试过不同的格式。我什至尝试过 Newspaper 和 Newspaper3k。最后,我尝试了lxml、html5lib和html.parser库,都无济于事。

任何建议都会有所帮助......请。

我的 HTML 源代码如下所示:

<meta name="description" content="Here is an exclusive we just got in regarding toda...." />
<meta property="og:description" content="Here is an exclusive we just got in regarding toda...." />
<meta property="article:section" content="Breaking News" />

我的 python 代码如下所示:

# Import requisite libraries
from bs4 import BeautifulSoup


# Start it up (and note I have also tried lxml and html.parser)
soup = BeautifulSoup(corpus, 'html5lib')
# corpus is holding data from Newspaper3k. This aspect works.


# Following is just me trying different ways to find the same 2 things:

# Retrieve description AKA summary
description = soup.find("meta",  property="og:description")  # 1st way
summary = soup.find("meta",  attrs={'name': "description"})  # 2nd way

# Retrieve category AKA section
category = soup.find("meta",  property='article:section')  # 1st way
section = soup.find("meta",  attrs={'article': "section"})  # 2nd way


# Test and return result
print(description["content"] if description else "No description given")
print(summary["content"] if summary else "No summary given")
print(category["content"] if category else "No category given")
print(section["content"] if section else "No section given")
  • 它总是返回:

    No description given
    No summary given
    No category given
    No section given
    

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup meta-tags


    【解决方案1】:

    好的...我解决了。问题是我使用的是从 Newspaper3k 中提取的语料库作为数据集。不要误会我的意思...正如标签上所说的那样有效...但是元标签不会在那里,因为它只会拉入文章正文和作者。

    但是,当我现在改为使用 BS4 来提取数据时,它实际上也提取了基础数据(而不仅仅是文章正文),这意味着它现在具有元标记。

    我们可以关闭这个,感谢您的耐心等待。

    正确的代码如下所示:

        url = urllib.request.urlopen('https://www.someurl.com/breakingnews/this-just-in/')
        content = url.read()
        soup = BeautifulSoup(content, 'lxml')
    
        description = soup.find("meta",  property="og:description")
        summary = soup.find("meta",  attrs={'name': "description"})
        category = soup.find("meta",  property='article:section')
    
        print(description["content"] if description else "No description given")
        print(summary["content"] if summary else "No summary given")
        print(category["content"] if category else "No category given")
    

    然后像以前一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-04
      • 2019-03-08
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多