在進(jìn)行網(wǎng)頁數(shù)據(jù)抓取時(shí)我們要先安裝一個(gè)模塊
requests
通過終端安裝如下圖
因?yàn)槲抑鞍惭b過了达吞,所以不會(huì)顯示安裝進(jìn)度條导狡,安裝也非常簡(jiǎn)單舀透,如果你配置好環(huán)境變量的話轧飞,你只需要執(zhí)行以下命令
pip install requests
如果提示要升級(jí)蛹含,就按下面升級(jí)pip
pip install --upgrade pip
安裝完模塊后我們正式開始進(jìn)行數(shù)據(jù)爬取
先說一下requests的用法毅厚,導(dǎo)入這個(gè)模塊后,你只需要調(diào)用一下get方法浦箱,就能獲取網(wǎng)頁的內(nèi)容了
例如吸耿,爬取我的博客首頁,這個(gè)單網(wǎng)頁
In [1]: import requests
In [2]: resp = requests.get("http://www.susmote.com")
In [3]: resp.encoding = "utf-8"
In [4]: type(resp.text)
Out[4]: str
In [5]: content = resp.text[0:100]
In [6]: print(content)
首先導(dǎo)入憎茂,然后調(diào)用get方法珍语,里面接你要爬取的網(wǎng)頁
注意:必須要加http:頭,不然會(huì)報(bào)錯(cuò)
然后在第三步竖幔,我們更改了默認(rèn)編碼板乙,這個(gè)取決于你要爬取網(wǎng)頁的編碼格式,如果不更改拳氢,極大可能會(huì)出行亂碼募逞,或是一些沒有看過的字符
在第五步,我們把爬取網(wǎng)頁內(nèi)容的前50個(gè)字符賦值給了content馋评,以便之后查看放接,因?yàn)榫W(wǎng)頁內(nèi)容太多,不能一次全部打印出來留特,所以我們決定切片輸出一部分內(nèi)容
最后一步纠脾,我們打印出剛才保存的一部分內(nèi)容
前面只是提前熟悉一下爬取數(shù)據(jù)的步驟,接下來我們通過列表字典批量獲取數(shù)據(jù)蜕青,然后把它保存為一個(gè)文件
首先定義一個(gè)字典苟蹈,存儲(chǔ)我們要抓取頁面的網(wǎng)址
urls_dict = {
'特克斯博客': 'http://www.susmote.com/',
'百度': 'http://www.baidu.com',
'xyz': 'www.susmote.com',
'特克斯博客歌單區(qū)1': 'https://www.susmote.com/?cate=13',
'特克斯博客歌單區(qū)2': 'https://www.susmote.com/?cate=13'
}
然后我們?cè)诙x一個(gè)列表,也是存儲(chǔ)抓取頁面的網(wǎng)址
urls_lst = [
('特克斯博客', 'http://www.susmote.com/'),
('百度', 'http://www.baidu.com'),
('xyz', 'www.susmote.com'),
('特克斯博客歌單區(qū)1', 'https://www.susmote.com/?cate=13'),
('特克斯博客歌單區(qū)2', 'https://www.susmote.com/?cate=13')
]
然后我們先利用字典來抓取
代碼如下:
利用字典抓取
crawled_urls_for_dict = set()
for ind, name in enumerate(urls_dict.keys()):
name_url = urls_dict[name]
if name_url in crawled_urls_for_dict:
print(ind, name, "已經(jīng)抓取過了.")
else:
try:
resp = requests.get(name_url)
except Exception as e:
print(ind, name, ":", str(e)[0:50])
continue
resp.encoding = "utf8"
content = resp.text
crawled_urls_for_dict.add(name_url)
with open("bydict_" + name + ".html", 'w', encoding='utf8') as f:
f.write(content)
print("抓取完成 : {} {}, 內(nèi)容長(zhǎng)度為{}".format(ind, name, len(content)))
首先定義一個(gè)空集合右核,以保存我們抓取完數(shù)據(jù)的網(wǎng)址慧脱,以避免重復(fù)抓取
后面我們通過for循環(huán)和枚舉,遍歷每一個(gè)字典的鍵和值贺喝,把每一抓取的網(wǎng)址存進(jìn)開始定義的集合crawled_urls_for_dict
然后我們判斷要抓取的網(wǎng)址菱鸥,是否已經(jīng)保存在集合中,如果存在躏鱼,就輸出已經(jīng)抓取過了
如果沒有氮采,再進(jìn)行后面的操作,在這里我們?yōu)榱朔乐钩绦虺鲥e(cuò)染苛,影響程序的整體運(yùn)行扳抽,我們?cè)谶@里使用了try except 語句來打印出錯(cuò)的異常,這樣能保證程序能完整運(yùn)行
然后無非和我之前說的一樣,改編碼格式贸呢,暫時(shí)保存內(nèi)容
只是最后我們通過創(chuàng)建一個(gè)文件來保存爬取下來的網(wǎng)頁文件镰烧,這個(gè)我就不詳細(xì)解釋了,無非就是加了個(gè)后綴
在后面我們打印抓取的網(wǎng)頁地址
for u in crawled_urls_for_dict:
print(u)
然后我們利用列表來抓取數(shù)據(jù)
代碼如下
# 利用列表抓取
crawled_urls_for_list = set()
for ind, tup in enumerate(urls_lst):
name = tup[0]
name_url = tup[1]
if name_url in crawled_urls_for_list:
print(ind, name, "已經(jīng)抓取過了.")
else:
try:
resp = requests.get(name_url)
except Exception as e:
print(ind, name, ":", str(e)[0:50])
continue
resp.encoding = "utf8"
content = resp.text
crawled_urls_for_list.add(name_url)
with open('bylist_' + name + ".html", "w", encoding='utf8') as f:
f.write(content)
print("抓取完成:{} {}, 內(nèi)容長(zhǎng)度為{}".format(ind, name, len(content)))
原理上跟前面的字典一樣楞陷,我就不做過多解釋了
只是要注意這是一個(gè)嵌套的列表怔鳖,遍歷的時(shí)候要注意一下
最后也是一樣
for u in crawled_urls_for_list:
print(u)
打印抓取過的數(shù)據(jù)
運(yùn)行結(jié)果如下圖
susmotedeMacBook-Air:FirstDatamining susmote$ python main.py
抓取完成 : 0 特克斯博客, 內(nèi)容長(zhǎng)度為26793
抓取完成 : 1 百度, 內(nèi)容長(zhǎng)度為2287
2 xyz : Invalid URL 'www.susmote.com': No schema supplied.
抓取完成 : 3 特克斯博客歌單區(qū)1, 內(nèi)容長(zhǎng)度為21728
4 特克斯博客歌單區(qū)2 已經(jīng)抓取過了.
http://www.susmote.com/
http://www.baidu.com
https://www.susmote.com/?cate=13
------------------------------------------------------------
抓取完成:0 特克斯博客, 內(nèi)容長(zhǎng)度為26793
抓取完成:1 百度, 內(nèi)容長(zhǎng)度為2287
2 xyz : Invalid URL 'www.susmote.com': No schema supplied.
抓取完成:3 特克斯博客歌單區(qū)1, 內(nèi)容長(zhǎng)度為21728
4 特克斯博客歌單區(qū)2 已經(jīng)抓取過了.
http://www.susmote.com/
http://www.baidu.com
https://www.susmote.com/?cate=13
文件目錄變化如下
用瀏覽器打開如下圖
特克斯博客 www.susmote.com
百度網(wǎng)站 www.baidu..com
到這里,簡(jiǎn)單的數(shù)據(jù)抓取就講完了
歡迎訪問我的官網(wǎng)