搜索
首页后端开发Python教程新浪新闻详情页的数据抓取实例

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

Jun 21, 2017 pm 03:23 PM
python新浪新闻爬虫详情

上一篇文章《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': '张迪 '}

以上是新浪新闻详情页的数据抓取实例的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python:编译器还是解释器?Python:编译器还是解释器?May 13, 2025 am 12:10 AM

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

python用于循环与循环时:何时使用哪个?python用于循环与循环时:何时使用哪个?May 13, 2025 am 12:07 AM

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

Python循环:最常见的错误Python循环:最常见的错误May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

对于循环和python中的循环时:每个循环的优点是什么?对于循环和python中的循环时:每个循环的优点是什么?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供应模拟性和可读性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境