Python很是適合用來開發網頁爬蟲,理由以下:
一、抓取網頁自己的接口
相比與其餘靜態編程語言,如java,c#,c++,python抓取網頁文檔的接口更簡潔;相比其餘動態腳本語言,如perl,shell,python的urllib包提供了較爲完整的訪問網頁文檔的API。(固然ruby也是很好的選擇)
此外,抓取網頁有時候須要模擬瀏覽器的行爲,不少網站對於生硬的爬蟲抓取都是封殺的。這是咱們須要模擬user agent的行爲構造合適的請求,譬如模擬用戶登錄、模擬session/cookie的存儲和設置。在python裏都有很是優秀的第三方包幫你搞定,如Requests,mechanizehtml
二、網頁抓取後的處理
抓取的網頁一般須要處理,好比過濾html標籤,提取文本等。python的beautifulsoap提供了簡潔的文檔處理功能,能用極短的代碼完成大部分文檔的處理。
其實以上功能不少語言和工具都能作,可是用python可以幹得最快,最乾淨。java
Life is short, you need python.node
PS:python2.x和python3.x有很大不一樣,本文只討論python3.x的爬蟲實現方法。python
<!--more-->mysql
URL管理器:管理待爬取的url集合和已爬取的url集合,傳送待爬取的url給網頁下載器。
網頁下載器(urllib):爬取url對應的網頁,存儲成字符串,傳送給網頁解析器。
網頁解析器(BeautifulSoup):解析出有價值的數據,存儲下來,同時補充url到URL管理器。c++
添加新的url到待爬取url集合中。正則表達式
判斷待添加的url是否在容器中(包括待爬取url集合和已爬取url集合)。redis
獲取待爬取的url。sql
判斷是否有待爬取的url。shell
將爬取完成的url從待爬取url集合移動到已爬取url集合。
一、內存(python內存)
待爬取url集合:set()
已爬取url集合:set()
二、關係數據庫(mysql)
urls(url, is_crawled)
三、緩存(redis)
待爬取url集合:set
已爬取url集合:set
大型互聯網公司,因爲緩存數據庫的高性能,通常把url存儲在緩存數據庫中。小型公司,通常把url存儲在內存中,若是想要永久存儲,則存儲到關係數據庫中。
將url對應的網頁下載到本地,存儲成一個文件或字符串。
新建baidu.py,內容以下:
import urllib.request response = urllib.request.urlopen('http://www.baidu.com') buff = response.read() html = buff.decode("utf8") print(html)
命令行中執行python baidu.py
,則能夠打印出獲取到的頁面。
上面的代碼,能夠修改成:
import urllib.request request = urllib.request.Request('http://www.baidu.com') response = urllib.request.urlopen(request) buff = response.read() html = buff.decode("utf8") print(html)
新建baidu2.py,內容以下:
import urllib.request import urllib.parse url = 'http://www.baidu.com' values = {'name': 'voidking','language': 'Python'} data = urllib.parse.urlencode(values).encode(encoding='utf-8',errors='ignore') headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0' } request = urllib.request.Request(url=url, data=data,headers=headers,method='GET') response = urllib.request.urlopen(request) buff = response.read() html = buff.decode("utf8") print(html)
咱們想要查看一下,咱們的請求是否真的攜帶了參數,因此須要使用fiddler。
打開fiddler以後,卻意外發現,上面的代碼會報錯504,不管是baidu.py仍是baidu2.py。
雖然python有報錯,可是在fiddler中,咱們能夠看到請求信息,確實攜帶了參數。
通過查找資料,發現python之前版本的Request都不支持代理環境下訪問https。可是,最近的版本應該支持了纔對。那麼,最簡單的辦法,就是換一個使用http協議的url來爬取,好比,換成http://www.csdn.net
。結果,依然報錯,只不過變成了400錯誤。
然而,然而,然而。。。神轉折出現了!!!
當我把url換成http://www.csdn.net/
後,請求成功!沒錯,就是在網址後面多加了一個斜槓/
。同理,把http://www.baidu.com
改爲http://www.baidu.com/
,請求也成功了!神奇!!!
import urllib.request import http.cookiejar # 建立cookie容器 cj = http.cookiejar.CookieJar() # 建立opener opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) # 給urllib.request安裝opener urllib.request.install_opener(opener) # 請求 request = urllib.request.Request('http://www.baidu.com/') response = urllib.request.urlopen(request) buff = response.read() html = buff.decode("utf8") print(html) print(cj)
從網頁中提取出有價值的數據和新的url列表。
爲了實現解析器,能夠選擇使用正則表達式、html.parser、BeautifulSoup、lxml等,這裏咱們選擇BeautifulSoup。
其中,正則表達式基於模糊匹配,而另外三種則是基於DOM結構化解析。
一、安裝,在命令行下執行pip install beautifulsoup4
。
二、測試
import bs4 print(bs4)
一、建立BeautifulSoup對象
import bs4 from bs4 import BeautifulSoup # 根據html網頁字符串建立BeautifulSoup對象 html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ soup = BeautifulSoup(html_doc) print(soup.prettify())
二、訪問節點
print(soup.title) print(soup.title.name) print(soup.title.string) print(soup.title.parent.name) print(soup.p) print(soup.p['class'])
三、指定tag、class或id
print(soup.find_all('a')) print(soup.find('a')) print(soup.find(class_='title')) print(soup.find(id="link3")) print(soup.find('p',class_='title'))
四、從文檔中找到全部<a>
標籤的連接
for link in soup.find_all('a'): print(link.get('href'))
出現了警告,根據提示,咱們在建立BeautifulSoup對象時,指定解析器便可。
soup = BeautifulSoup(html_doc,'html.parser')
五、從文檔中獲取全部文字內容
print(soup.get_text())
六、正則匹配
link_node = soup.find('a',href=re.compile(r"til")) print(link_node)
python爬蟲基礎知識,至此足夠,接下來,在實戰中學習更高級的知識。
Python開發簡單爬蟲
http://www.imooc.com/learn/563
The Python Standard Library
https://docs.python.org/3/lib...
Beautiful Soup 4.2.0 文檔
https://www.crummy.com/softwa...
爲何python適合寫爬蟲?
http://www.cnblogs.com/benzon...
如何學習Python爬蟲[入門篇]?
https://zhuanlan.zhihu.com/p/...
你須要這些:Python3.x爬蟲學習資料整理
https://zhuanlan.zhihu.com/p/...
如何入門 Python 爬蟲?
https://www.zhihu.com/questio...
Python3.X 抓取網絡資源
http://www.open-open.com/lib/...
python網絡請求和"HTTP Error 504:Fiddler - Receive Failure"
http://blog.csdn.net/guoguo52...
怎麼使用Fiddler抓取本身寫的爬蟲的包?
https://www.zhihu.com/questio...
fiddler對python腳本抓取https包時發生了錯誤?
https://www.zhihu.com/questio...
HTTPS和HTTP的區別
http://blog.csdn.net/whatday/...