写一个简单的爬虫来批量爬取新浪网的新闻
生活随笔
收集整理的這篇文章主要介紹了
写一个简单的爬虫来批量爬取新浪网的新闻
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
如標(biāo)題,學(xué)習(xí)爬蟲也有一段時(shí)間了,今天來爬取一下新浪網(wǎng)的新聞(其實(shí)之前自己爬過,但是隔了好久發(fā)現(xiàn)新浪網(wǎng)的網(wǎng)頁結(jié)構(gòu)有一些變化導(dǎo)致之前的爬蟲失效了,這兩天進(jìn)行了一下代碼更新),話不多說,進(jìn)入正題。
工具:Anaconda
先進(jìn)入該頁,新浪新聞:http://news.sina.com.cn/china/
往下翻,找到這樣的最新消息
先爬取單個(gè)頁面的信息:(隨便點(diǎn)一個(gè)進(jìn)去),
該新聞網(wǎng)址:http://news.sina.com.cn/c/nd/2018-06-08/doc-ihcscwxa1809510.shtml
用開發(fā)者模式分析網(wǎng)頁結(jié)構(gòu)之后,我要獲取新聞標(biāo)題,新聞時(shí)間,新聞來源,文章內(nèi)容,作者姓名,評(píng)論總數(shù)等,代碼如下(主要用的是BeautifulSoup模塊):
import requests from bs4 import BeautifulSoup from datetime import datetime import json res=requests.get('http://news.sina.com.cn/c/nd/2018-06-08/doc-ihcscwxa1809510.shtml') res.encoding='utf-8' soup=BeautifulSoup(res.text,'html.parser') title=soup.select('.main-title')[0].text #timesource1=soup.select('.date-source')[0].text.split('\n')[1] #獲取時(shí)間 timesource=soup.select('.date-source span')[0].text #獲取時(shí)間 dt=datetime.strptime(timesource,'%Y年%m月%d日 %H:%M') dt.strftime('%Y-%m-%d') place=soup.select('.date-source a')[0].text #獲取新聞來源 article=[] #獲取文章內(nèi)容 for p in soup.select('#article p')[:-1]:article.append(p.text.strip()) articleall=' '.join(article) editor=soup.select('#article p')[-1].text.strip('責(zé)任編輯:') #獲取作者姓名 comments=requests.get('http://comment5.news.sina.com.cn/page/info?version=1&format=json&\ channel=gn&newsid=comos-hcscwxa1809510&group=undefined&compress=0&ie=utf-8&\ oe=utf-8&page=1&page_size=3&t_size=3&h_size=3&thread=1') #print(comments.text) jd=json.loads(comments.text) #用jason解析器 comment_num=jd['result']['count']['total'] #獲得評(píng)論總數(shù)將上述單頁面的代碼進(jìn)行封裝整理:?
newsurl='http://news.sina.com.cn/c/nd/2018-06-08/doc-ihcscwxa1809510.shtml' commenturl='http://comment5.news.sina.com.cn/page/info?version=1&format=json&channel=gn&newsid=comos-{}&group=undefined&compress=0&ie=utf-8&oe=utf-8&page=1&page_size=3&t_size=3&h_size=3&thread=1' def getcommentcounts(newsurl): #獲取評(píng)論數(shù)m=re.compile('doc-i(.*?).shtml').findall(newsurl)newsid=m[0]comments=requests.get(commenturl.format(newsid))jd=json.loads(comments.text)return jd['result']['count']['total']def getnewsdetail(newsurl): #獲得單頁的新聞內(nèi)容result={}res=requests.get(newsurl)res.encoding='utf-8'soup=BeautifulSoup(res.text,'html.parser')result['title']=soup.select('.main-title')[0].text #標(biāo)題timesource=soup.select('.date-source span')[0].text result['time']=datetime.strptime(timesource,'%Y年%m月%d日 %H:%M').strftime('%Y-%m-%d') #時(shí)間result['place']=soup.select('.source')[0].text #來源article=[] #獲取文章內(nèi)容for p in soup.select('#article p')[:-1]:article.append(p.text.strip())articleall=' '.join(article)result['article']=articleallresult['editor']=soup.select('#article p')[-1].text.strip('責(zé)任編輯:') #獲取作者姓名result['comment_num']=getcommentcounts(newsurl)return result 上面的代碼搞定了每一個(gè)網(wǎng)址所包含的具體的新聞內(nèi)容,但是我們是要批量爬取多頁的新聞內(nèi)容,每一頁大概并列包含了20多個(gè)新聞,所以對(duì)網(wǎng)頁的開發(fā)者模式進(jìn)行分析后先獲取每一頁的所有新聞對(duì)應(yīng)的url,如下: url='http://api.roll.news.sina.com.cn/zt_list?channel=news&cat_1=gnxw&cat_2==gdxw1||=gatxw||=zs-pl||=mtjj&level==1||=2&show_ext=1&show_all=1&show_num=22&tag=1&format=json&page={}&callback=newsloadercallback&_=1528548757769' def parseListLinks(url):newsdetail=[]res=requests.get(url)jd=json.loads(res.text.lstrip(' newsloadercallback(').rstrip(');'))for ent in jd['result']['data']:newsdetail.append(getnewsdetail(ent['url']))return newsdetail 得到每一頁的所有新聞的url之后,我們要獲得多頁的所有新聞,分析url可得,每一頁有網(wǎng)址上的page來進(jìn)行控制,那就可以寫一個(gè)循環(huán)(批量抓取10頁的新聞信息放在news_total里): news_total=[] for i in range(1,10):newsurl=url.format(i)newsary=parseListLinks(newsurl)news_total.extend(newsary) 最后將結(jié)果用pandas進(jìn)行整理,當(dāng)然,整理完了之后也可以保存成excel方便以后閱讀: import pandas as pd df=pd.DataFrame(news_total) 最后結(jié)果如下所示:?
?
總結(jié)
以上是生活随笔為你收集整理的写一个简单的爬虫来批量爬取新浪网的新闻的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: react native关于自定义字体
- 下一篇: 密码、私钥、keystore与助记词之间