前言
網(wǎng)絡(luò)爬蟲(chóng)(又被稱為網(wǎng)頁(yè)蜘蛛,網(wǎng)絡(luò)機(jī)器人,在FOAF社區(qū)中間,更經(jīng)常的稱為網(wǎng)頁(yè)追逐者),是一種按照一定的規(guī)則,自動(dòng)地抓取萬(wàn)維網(wǎng)信息的程序或者腳本。最近對(duì)python爬蟲(chóng)有了強(qiáng)烈地興趣,在此分享自己的學(xué)習(xí)路徑,歡迎大家提出建議。我們相互交流,共同進(jìn)步。話不多說(shuō)了,來(lái)一起看看詳細(xì)的介紹:
1.開(kāi)發(fā)工具
筆者使用的工具是sublime text3,它的短小精悍(可能男人們都不喜歡這個(gè)詞)使我十分著迷。推薦大家使用,當(dāng)然如果你的電腦配置不錯(cuò),pycharm可能更加適合你。
sublime text3搭建python開(kāi)發(fā)環(huán)境推薦查看這篇文章:
[sublime搭建python開(kāi)發(fā)環(huán)境][//www.jb51.net/article/51838.htm]
2.爬蟲(chóng)介紹
爬蟲(chóng)顧名思義,就是像蟲(chóng)子一樣,爬在Internet這張大網(wǎng)上。如此,我們便可以獲取自己想要的東西。
既然要爬在Internet上,那么我們就需要了解URL,法號(hào)“統(tǒng)一資源定位器”,小名“鏈接”。其結(jié)構(gòu)主要由三部分組成:
(1)協(xié)議:如我們?cè)诰W(wǎng)址中常見(jiàn)的HTTP協(xié)議。
(2)域名或者IP地址:域名,如:www.baidu.com,IP地址,即將域名解析后對(duì)應(yīng)的IP。
(3)路徑:即目錄或者文件等。
3.urllib開(kāi)發(fā)最簡(jiǎn)單的爬蟲(chóng)
(1)urllib簡(jiǎn)介
| Module | Introduce |
|---|---|
| urllib.error | Exception classes raised by urllib.request. |
| urllib.parse | Parse URLs into or assemble them from components. |
| urllib.request | Extensible library for opening URLs. |
| urllib.response | Response classes used by urllib. |
| urllib.robotparser | Load a robots.txt file and answer questions about fetchability of other URLs. |
(2)開(kāi)發(fā)最簡(jiǎn)單的爬蟲(chóng)
百度首頁(yè)簡(jiǎn)潔大方,很適合我們爬蟲(chóng)。
爬蟲(chóng)代碼如下:
from urllib import requestdef visit_baidu(): URL = "http://www.baidu.com" # open the URL req = request.urlopen(URL) # read the URL html = req.read() # decode the URL to utf-8 html = html.decode("utf_8") print(html)if __name__ == '__main__': visit_baidu()結(jié)果如下圖:

我們可以通過(guò)在百度首頁(yè)空白處右擊,查看審查元素來(lái)和我們的運(yùn)行結(jié)果對(duì)比。
當(dāng)然,request也可以生成一個(gè)request對(duì)象,這個(gè)對(duì)象可以用urlopen方法打開(kāi)。
代碼如下:
from urllib import requestdef vists_baidu(): # create a request obkect req = request.Request('http://www.baidu.com') # open the request object response = request.urlopen(req) # read the response html = response.read() html = html.decode('utf-8') print(html)if __name__ == '__main__': vists_baidu()
新聞熱點(diǎn)
疑難解答
圖片精選