本文摘自php中文网,作者PHP中文网,侵删。
上一篇文章《Python爬虫:抓取新浪新闻数据》详细解说了如何抓取新浪新闻详情页的相关数据,但代码的构建不利于后续扩展,每次抓取新的详情页时都需要重新写一遍,因此,我们需要将其整理成函数,方便直接调用。详情页抓取的6个数据:新闻标题、评论数、时间、来源、正文、责任编辑。
首先,我们先将评论数整理成函数形式表示:
1 | 1 import requests 2 import json 3 import re 4 5 comments_url = '{}&group=&compress=0&ie=utf-8&oe=utf-8&page=1&page_size=20' 6 7 def getCommentsCount(newsURL): 8 ID = re.search( 'doc-i(.+).shtml' , newsURL) 9 newsID = ID.group(1)10 commentsURL = requests.get(comments_url.format(newsID))11 commentsTotal = json.loads(commentsURL.text.strip( 'var data=' ))12 return commentsTotal[ 'result' ][ 'count' ][ 'total' ]13 14 news = '' 15 print (getCommentsCount(news))
|
第5行comments_url,在上一篇中,我们知道评论链接中有新闻ID,不同新闻的评论数通过该新闻ID的变换而变换,因此我们将其格式化,新闻ID处用大括号{}来替代;
定义获取评论数的函数getCommentsCount,通过正则来查找匹配的新闻ID,然后将获取的新闻链接存储进变量commentsURL中,通过解码JS来得到最终的评论数commentsTotal;
然后,我们只需输入新的新闻链接,便可直接调用函数getCommentsCount来获取评论数。
最后,我们将需要抓取的6个数据均整理到一个函数getNewsDetail中。如下:
1 | 1 from bs4 import BeautifulSoup 2 import requests 3 from datetime import datetime 4 import json 5 import re 6 7 comments_url = '{}&group=&compress=0&ie=utf-8&oe=utf-8&page=1&page_size=20' 8 9 def getCommentsCount(newsURL):10 ID = re.search( 'doc-i(.+).shtml' , newsURL)11 newsID = ID.group(1)12 commentsURL = requests.get(comments_url.format(newsID))13 commentsTotal = json.loads(commentsURL.text.strip( 'var data=' ))14 return commentsTotal[ 'result' ][ 'count' ][ 'total' ]15 16 # news = 'http://news.sina.com.cn/c/nd/2017-05-14/doc-ifyfeius7904403.shtml' 17 # print (getCommentsCount(news))18 19 def getNewsDetail(news_url):20 result = {}21 web_data = requests.get(news_url)22 web_data.encoding = 'utf-8' 23 soup = BeautifulSoup(web_data.text, 'lxml' )24 result[ 'title' ] = soup.select( '#artibodyTitle' )[0].text25 result[ 'comments' ] = getCommentsCount(news_url)26 time = soup.select( '.time-source' )[0].contents[0].strip()27 result[ 'dt' ] = datetime. strptime (time, '%Y年%m月%d日%H:%M' )28 result[ 'source' ] = soup.select( '.time-source span span a' )[0].text29 result[ 'article' ] = ' ' .join([p.text.strip() for p in soup.select( '#artibody p' )[:-1]])30 result[ 'editor' ] = soup.select( '.article-editor' )[0].text.lstrip( '责任编辑:' )31 return result32 33 print (getNewsDetail( '' ))
|
在函数getNewsDetail中,获取需要抓取的6个数据,放在result中:
而后输入自己想要获取数据的新闻链接,调用该函数即可。
部分运行结果:
{'title': '浙大附中开课教咏春 “教头”系叶问第三代弟子', 'comments': 618, 'dt': datetime.datetime(2017, 5, 14, 7, 22), 'source': '中国新闻网', 'article': '原标题:浙大附中开课教咏春 “教头”系叶问......来源:钱江晚报', 'editor': '张迪 '}
以上就是新浪新闻详情页的数据抓取实例的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
使用Python通过win32 com实现word文档的写入与保存方法
Python关于变量赋值的秘密介绍
成为Python大牛必不可少的几款编辑器
Python怎么画正方形螺旋线
Python中高阶函数实现剪枝函数的方法
Python通过matplotlib简单绘制动画实例
Python输出怎么取消空格
Python编程快速上手第六章实践项目参考code
导入Python标准数学函数模块的语句是什么
Python字符编码讲解
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 新浪新闻详情页的数据抓取实例