欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

新浪新闻详情页的数据抓取实例

程序员文章站 2022-04-24 14:45:23
...
上一篇文章《Python爬虫:抓取新浪新闻数据》详细解说了如何抓取新浪新闻详情页的相关数据,但代码的构建不利于后续扩展,每次抓取新的详情页时都需要重新写一遍,因此,我们需要将其整理成函数,方便直接调用。

详情页抓取的6个数据:新闻标题、评论数、时间、来源、正文、责任编辑。

首先,我们先将评论数整理成函数形式表示:

 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 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中:

  • result['title']是获取新闻标题;

  • resul['comments']是获取评论数,可以直接调用我们开头定义的评论数函数getCommentsCount;

  • result['dt']是获取时间; result['source']是获取来源;

  • result['article']是获取正文;

  • result['editor']是获取责任编辑。

而后输入自己想要获取数据的新闻链接,调用该函数即可。

部分运行结果:

{'title': '浙大附中开课教咏春 “教头”系叶问第三代弟子', 'comments': 618, 'dt': datetime.datetime(2017, 5, 14, 7, 22), 'source': '中国新闻网', 'article': '原标题:浙大附中开课教咏春 “教头”系叶问......来源:钱江晚报', 'editor': '张迪 '}

以上就是新浪新闻详情页的数据抓取实例的详细内容,更多请关注其它相关文章!