如何仅提取文章正文的某些部分?
Posted
技术标签:
【中文标题】如何仅提取文章正文的某些部分?【英文标题】:How can I extract only certain parts of the body of an article? 【发布时间】:2019-07-13 20:18:09 【问题描述】:在我的text_scraper(page_soup)
中,我意识到最后我得到了与我的文章完全无关的不相关信息。什么是消除不相关信息的通用方法?
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import re
# Initializing our dictionary
dictionary =
# Initializing our url key
url_key = 'url'
dictionary.setdefault(url_key, [])
# Initializing our text key
text_key = 'text'
dictionary.setdefault(text_key, [])
def text_scraper(page_soup):
text_body = ''
# Returns the text of p tags, we stopped it at -5 bc that's when the text is irrelevant to the article
for p in page_soup.find_all('p'):
text_body += p.text
return(text_body)
def article_scraper(url):
# Opening up the connection, grabbing the page
uClient = uReq(url)
page_html = uClient.read()
uClient.close()
# HTML parsing
page_soup = soup(page_html, "html.parser")
dictionary['url'].append(url)
dictionary['text'] = text_scraper(page_soup)
return dictionary
articles_zero = 'https://www.sfchronicle.com/news/bayarea/heatherknight/article/Special-education-teacher-a-prime-example-of-13560483.php'
article = article_scraper(articles_zero)
article
【问题讨论】:
你想抓取文章的哪一部分? 直到这一段:“这座城市需要尽其所能来留住像 Torres Esquer 这样的教师。恰好有 1.85 亿美元的免费资金坐在那里帮助它做到这一点。” @Andy 我的回答对你有好处吗?如果是,你能接受吗? 【参考方案1】:如果你只想要与文章相关的文本,你可以在你的text_scraper
方法中调整你的指针,只刮<section>
中的<p>
标签:
def text_scraper(page_soup):
text_body = ''
# Find only the text related to the article:
article_section = page_soup.find('section','class':'body')
# Returns the text of p tags, we stopped it at -5 bc that's when the text is irrelevant to the article
for p in article_section.find_all('p'):
if p.previousSibling and p.previousSibling.name is not 'em':
text_body += p.text
return(text_body)
然后文章将返回,页脚内没有文字(Heather Knight 是一个专栏作家 [...] 和他们的斗争。)
编辑:添加了对父级的测试以避免最后一部分旧金山纪事[...]Twitter:@hknightsf
【讨论】:
以上是关于如何仅提取文章正文的某些部分?的主要内容,如果未能解决你的问题,请参考以下文章