如何抓取新闻内容并删除不相关的部分



我的目标是使用BeautifulSoup和for循环抓取100条新闻文本,并将文本存储到我的文章中。我希望我的文章应该只包含新闻文章的内容,我发现它们都有h属性。但是,我得到的结果包含许多不相关的部分,例如:"感谢您与我们联系。我们已收到您的提交"和"这个故事已被分享了 205,105 次。 205,105"等。

另一个问题是,当我打印(myarticle[0](时,它给了我很多新闻文章,但我希望它应该只给我 1 篇文章。

我想知道如何删除不相关的部分,只保留我们从新闻网络上阅读的主要内容。我该如何调整代码,以便在我打印(myarticle[0](时,它给了我第一篇新闻文章。

100 篇新闻文章中的一篇位于此页面上: https://nypost.com/2020/04/21/missouri-sues-china-over-coronavirus-deceit/

我想抓取的其他新闻文章在这个网站上: https://nypost.com/search/China+COVID-19/page/1/?orderby=relevance

以下是与我的问题相关的代码行。

for pagelink in pagelinks:
#get page text
page = requests.get(pagelink)
#parse with BeautifulSoup
soup = bs(page.text, 'lxml')
articletext = soup.find_all('p')
for paragraph in articletext[:-1]:
#get the text only
text = paragraph.get_text()
paragraphtext.append(text)
#combine all paragraphs into an article
thearticle.append(paragraphtext)
# join paragraphs to re-create the article            
myarticle = [''.join(article) for article in thearticle]
#show the first string of the list
print(myarticle[0])
soup.find_all('p')

在这里,您可以在网页中找到所有P标签元素。P是大多数文本使用的非常常见的标签,这就是为什么您找到非文章文本的原因。

我会首先找到文章的包含div,然后获取文本,如下所示:

container = soup.find("div", class_=['entry-content', 'entry-content-read-more'])
articletext = container.find_all('p')

最新更新