1. 程式人生 > >【轉】寫一個簡單的爬蟲來批量爬取新浪網的新聞

【轉】寫一個簡單的爬蟲來批量爬取新浪網的新聞

工具:Anaconda

先進入該頁,新浪新聞:http://news.sina.com.cn/china/

往下翻,找到這樣的最新訊息

先爬取單個頁面的資訊:(隨便點一個進去),

該新聞網址:http://news.sina.com.cn/c/nd/2018-06-08/doc-ihcscwxa1809510.shtml

用開發者模式分析網頁結構之後,我要獲取新聞標題,新聞時間,新聞來源,文章內容,作者姓名,評論總數等,程式碼如下(主要用的是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] #獲取時間 timesource=soup.select('
.date-source span')[0].text #獲取時間 dt=datetime.strptime(timesource,'%Y年%m月%d日 %H:%M') dt.strftime('%Y-%m-%d') place=soup.select('.date-source a')[0].text #獲取新聞來源 article=[] #獲取文章內容 for p in soup.select('#article p')[:-1]: article.append(p.text.strip()) articleall
=' '.join(article) editor=soup.select('#article p')[-1].text.strip('責任編輯:') #獲取作者姓名 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'] #獲得評論總數

將上述單頁面的程式碼進行封裝整理:

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):            #獲取評論數
    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):                                        #獲得單頁的新聞內容
    result={}
    res=requests.get(newsurl)
    res.encoding='utf-8'
    soup=BeautifulSoup(res.text,'html.parser')
    result['title']=soup.select('.main-title')[0].text      #標題
    timesource=soup.select('.date-source span')[0].text  
    result['time']=datetime.strptime(timesource,'%Y年%m月%d日 %H:%M').strftime('%Y-%m-%d')              #時間
    result['place']=soup.select('.source')[0].text       #來源
    article=[]                                   #獲取文章內容
    for p in soup.select('#article p')[:-1]:
        article.append(p.text.strip())
    articleall=' '.join(article)
    result['article']=articleall
    result['editor']=soup.select('#article p')[-1].text.strip('責任編輯:')     #獲取作者姓名
    result['comment_num']=getcommentcounts(newsurl)
    return result

上面的程式碼搞定了每一個網址所包含的具體的新聞內容,但是我們是要批量爬取多頁的新聞內容,每一頁大概並列包含了20多個新聞,所以對網頁的開發者模式進行分析後先獲取每一頁的所有新聞對應的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可得,每一頁有網址上的page來進行控制,那就可以寫一個迴圈(批量抓取10頁的新聞資訊放在news_total裡):

news_total=[]
for i in range(1,10):
    newsurl=url.format(i)
    newsary=parseListLinks(newsurl)
    news_total.extend(newsary)

最後將結果用pandas進行整理,當然,整理完了之後也可以儲存成excel方便以後閱讀:

import pandas as pd
df=pd.DataFrame(news_total)

最後結果如下所示:

 

 

 以上轉自https://blog.csdn.net/weixin_42243942/article/details/80639040