python爬虫智能解析之newspaper

前言:

最近抓取了某查新闻舆情维度的数据,业务需求做一个情感分析,需要抓取相关链接的正文(因某查抓下来的只有摘要),新闻舆情的链接已经抓下来了,但是如下图所示这么多网站:

在这里插入图片描述我总不能每个网站写一个爬虫抓正文吧,那不得累死!于是想起来之前听过的智能化解析,遂学习一番,现需求任务已完成,在此做个记录总结与分享.

1. newspaper简介、特点及安装

2. newspaper的使用

  • 官方文档给出的是英文网站,上代码感受一下

    >>> from newspaper import Article>>> url = 'http://fox13now.com/2013/12/30/new-year-new-laws-obamacare-pot-guns-and-drones/'
    >>> article = Article(url)>>> article.download()>>> article.html
    '>>> article.parse()>>> article.authors
    ['Leigh Ann Caldwell', 'John Honway']>>> article.publish_date
    datetime.datetime(2013, 12, 30, 0, 0)>>> article.text
    'Washington (CNN) -- Not everyone subscribes to a New Year's resolution...'>>> article.top_image
    'http://someCDN.com/blah/blah/blah/file.png'>>> article.movies
    ['http://youtube.com/path/to/link.com', ...]>>> article.nlp()>>> article.keywords
    ['New Years', 'resolution', ...]>>> article.summary
    'The study shows that 93% of people ...'
    

    可以看到,首先要导入Article类,直接传入url参数,其次调用download()方法,将网页加载出来,然后调用parse()方法对网页内容进行智能解析,可以解析出来authors,publish_date,title,text,image,movies等等.

    另外还有个nlp()方法,可以提取keywords,summary等等.详细的可以查看官方文档.

  • 我需要抓取的是中文网站,Article中还需传入language,支持的语言如下:

    >>> import newspaper
    >>> newspaper.languages()Your available languages are:input code		full namear			  Arabicbe			  Belarusianbg			  Bulgarianda			  Danishde			  Germanel			  Greeken			  Englishes			  Spanishet			  Estonianfa			  Persianfi			  Finnishfr			  Frenchhe			  Hebrewhi			  Hindihr			  Croatianhu			  Hungarianid			  Indonesianit			  Italianja			  Japaneseko			  Koreanmk			  Macedoniannb			  Norwegian (Bokmål)nl			  Dutchno			  Norwegianpl			  Polishpt			  Portuguesero			  Romanianru			  Russiansl			  Sloveniansr			  Serbiansv			  Swedishsw			  Swahilitr			  Turkishuk			  Ukrainianvi			  Vietnamesezh			  Chinese
    
  • 直接上代码:

    from newspaper import Articleurl = ''
    try:article = Article(url, language='zh')article.download()print('html:', article.html)article.parse()print('authors:', article.authors)print('title:', article.title)print('date:', article.publish_date)print('text:', article.text)print('text_len:', len(article.text))print('top image:', article.top_image)print('images:', article.images)print('movies:', article.movies)# article.nlp()# print('keywords:', article.keywords)# print('summary:', article.summary)except newspaper.article.ArticleException:print(e)
    

    如果download()出错,会抛出一个newspaper.article.ArticleException的异常.

  • 到这里就结束啦,虽然很简单,但是newspaper确实给我省了不少事情,不过有一些特殊的网站提取不到,准确率还算可以吧.

  • 还有一个Diffbot,好像更好用,只是需要工作邮箱,各种原因注册不上,试用期两周之后会收费.


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部