1. 程式人生 > >python3程式設計07-爬蟲實戰:爬取新聞網站資訊3

python3程式設計07-爬蟲實戰:爬取新聞網站資訊3

本篇部落格在爬取新聞網站資訊2的基礎上進行。

 

主要內容如下:

1.定義獲取一頁20條連結內容的函式

2.構造多個分頁連結

3.抓取多個分頁連結新聞內容

4.用pandas整理爬取的資料

5.儲存資料到csv檔案

6.Scrapy的安裝

 

1.定義獲取一頁20條連結內容的函式

#定義獲取一頁20條連結內容的函式
def parseListLinks(url):
    newsdetails = []
    res = requests.get(url)
    jd = json.loads(res.text)
    #獲取一個頁面所有連結(20個左右)
    for ent in jd['result']['data']:
        #getNewsDetail為獲取一個連結內容詳情
        newsdetails.append(getNewsDetail(ent['url']))
    return newsdetails
#測試
url = 'https://feed.sina.com.cn/api/roll/get?pageid=121&lid=1356&num=20&versionNumber=1.2.4&page=1&encode=utf-8'
parseListLinks(url)

 

 

2.構造多個分頁連結 

#構造多個分頁連結
pageurl = "https://feed.sina.com.cn/api/roll/get?pageid=121&lid=1356&num=20&versionNumber=1.2.4&page={}&encode=utf-8"
for i in range(1,10):
    newsurl = pageurl.format(i)
    print(newsurl)

 

 

3.抓取多個分頁連結新聞內容

#抓取多個分頁連結新聞內容
import requests
url = 'https://feed.sina.com.cn/api/roll/get?pageid=121&lid=1356&num=20&versionNumber=1.2.4&page={}&encode=utf-8'
news_total = []
for i in range(1,3):
    newsurl = url.format(i)
    newsary = parseListLinks(url)
    news_total.extend(newsary)
#測試列印抓取的兩個頁面
print(news_total)

4.用pandas整理爬取的資料

Pandas 是python的一個數據分析包(Python Data Analysis Library),這裡我們用到pandas的DataFrame函式將爬取出來的資料整理成二維的表格型資料結構。

安裝pandas套件:進入cmd命令列,輸入以下命令安裝

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pandas

#用pandas整理爬取出的資料
import pandas
df = pandas.DataFrame(news_total)
#檢視後5行資料
df.tail()

 

5.儲存資料到csv檔案

用to_csv函式,將資料存放在csv檔案中,"ruiyigongfang.csv"為我們匯出的檔名稱,存放在jupyter notebook啟動的根目錄下,一般為C:\Users\Administrator目錄下。

檢視ruiyigongfang.csv檔案內容

 

至此,已經完成了用python3爬取新聞網站資訊的專案。

總結一下:

爬蟲主要流程為分為三個階段:

下載資料:用到requests套件,通過requests.get('url')方法獲取到了網頁資訊

提取資料:用到BeautifulSoup4套件,通過soup.select('xxx')來解析得到關係的內容;

儲存資料:通過pandas套件整理成二維資料結構的資料,再通過to_csv()函式將資料以csv格式儲存在本地。

 

--------------------------------------------------------------------------------------------

接下來還會有第二個python爬蟲專案,待下次部落格更新!

這裡先介紹一個簡單、功能強大的爬蟲框架Scrapy的安裝,為後面專案做好準備。

Scrapy安裝

環境:windows系統、python3
步驟:
1.安裝wheel: 

py -3 -m pip install wheel

2.安裝lxml:

py -3 -m pip install lxml

3.安裝Twisted:
下載Twisted:https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted

注意:下載的版本要與安裝的python版本與電腦位數一致,python3.7就選擇cp37, 其他版本依次類推 例如:

安裝Twisted:

pip install xxx/xxx/Twistedxxx

注意:xxx/xxx/Twistedxxx為下載的twisted檔案的所在絕對路徑。例如,下載的檔案放在D:\目錄下,檔名為Twisted‑18.9.0‑cp37‑cp37m‑win_amd64.whl

命令應該為pip install D:\Twisted‑18.9.0‑cp37‑cp37m‑win_amd64.whl


4.安裝Scrapy:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple scrapy


5.安裝win32py
下載:https://github.com/mhammond/pywin32/releases,注意要下載和python版本與電腦位數一致的檔案
安裝:雙擊pywin32-224.win-amd64-py3.7.exe檔案安裝

6.驗證

scrapy -h


說明:
安裝Scrapy依賴於wheel、lxml、Twisted模組
執行Scrapy依賴於win32py

 

 

完成!   enjoy it!