【发布时间】: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