繁体   English   中英

Python:(Beautifulsoup)如何将从html新闻文章中提取的文本限制为仅新闻文章。

[英]Python: (Beautifulsoup) How to limit extracted text from a html news article to only the news article.

我编写了使用BeautifulSoup的测试代码。

url = "http://www.dailymail.co.uk/news/article-3795511/Harry-Potter-sale-half-million-pound-house-Iconic-Privet-Drive-market-suburban-Berkshire-complete-cupboard-stairs-one-magical-boy.html"    
html = urllib.request.urlopen(url).read()  
soup = BeautifulSoup(html,"lxml")
for n in soup.find_all('p'):
    print(n.get_text())

它可以正常工作,但也可以检索不属于新闻文章的文本,例如发布时间,评论数量,版权等。

我希望它仅从新闻文章本身中检索文本,对此怎么办?

您不仅需要定位p标记,还需要更具体地定位。 尝试查找div class="article"或类似的内容,然后仅从那里获取段落

专注于刮文章的newspaper图书馆可能会给您带来更好的运气。

如果仅谈论BeautifulSoup ,则一种更接近所需结果并具有更多相关段落的选项是在div元素的上下文中使用itemprop="articleBody"属性找到它们:

article_body = soup.find(itemprop="articleBody")
for p in article_body.find_all("p"):
    print(p.get_text())

具体来说,您需要使用articleBody class捕获div ,因此:

import urllib.request
from bs4 import BeautifulSoup

url = "http://www.dailymail.co.uk/news/article-3795511/Harry-Potter-sale-half-million-pound-house-Iconic-Privet-Drive-market-suburban-Berkshire-complete-cupboard-stairs-one-magical-boy.html"    
html = urllib.request.urlopen(url).read()  
soup = BeautifulSoup(html,"lxml")
for n in soup.find_all('div', attrs={'itemprop':"articleBody"}):
    print(n.get_text())

对SO的回应不仅适合您,还适合来自google搜索等的人。 如您所见, attrs是一个命令,然后可以根据需要传递更多的属性/值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM