本文梳理了網頁解析、抓包、爬蟲基本流程等基礎知識。全文約 6250 字,讀完可能需要 9 分鐘。?
作者:voidking?
前言
Python 非常適合用來開發網頁爬蟲,理由如下:
1、抓取網頁本身的接口
相比與其他靜態編程語言,如 java , c#, c ++, python 抓取網頁文檔的接口更簡潔;相比其他動態腳本語言,如 perl , shell , python 的 urllib 包提供了較為完整的訪問網頁文檔的 API 。(當然 ruby 也是很好的選擇)
此外,抓取網頁有時候需要模擬瀏覽器的行為,很多網站對于生硬的爬蟲抓取都是封殺的。這是我們需要模擬 user agent的行為構造合適的請求,譬如模擬用戶登陸、模擬session/cookie的存儲和設置。在python里都有非常優秀的第三方包幫你搞定,如Requests,mechanize。
2、網頁抓取后的處理
抓取的網頁通常需要處理,比如過濾 html 標簽,提取文本等。 python 的 beautifulsoap 提供了簡潔的文檔處理功能,能用極短的代碼完成大部分文檔的處理。
其實以上功能很多語言和工具都能做,但是用 python 能夠干得最快,最干凈。
Life is short , you need python.?
PS :python 2. x 和 python 3. x 有很大不同,本文只討論 python 3. x 的爬蟲實現方法。
爬蟲架構
架構組成
URL 管理器:管理待爬取的 url 集合和已爬取的 url 集合,傳送待爬取的 url 給網頁下載器。
網頁下載器( urllib ):爬取 url 對應的網頁,存儲成字符串,傳送給網頁解析器。
網頁解析器( BeautifulSoup ):解析出有價值的數據,存儲下來,同時補充 url 到 URL 管理器。
運行流程
URL 管理器
基本功能
添加新的 url 到待爬取 url 集合中。
判斷待添加的 url 是否在容器中(包括待爬取 url 集合和已爬取 url 集合)。
獲取待爬取的 url 。
判斷是否有待爬取的 url 。
將爬取完成的 url 從待爬取 url 集合移動到已爬取 url 集合。
存儲方式
1、內存( python 內存) 待爬取 url 集合:set() 已爬取 url 集合:set()
2、關系數據庫( mysql ) urls( url , is_crawled)
3、緩存( redis ) 待爬取 url 集合: set() 已爬取 url 集合: set()
大型互聯網公司,由于緩存數據庫的高性能,一般把 url 存儲在緩存數據庫中。小型公司,一般把 url 存儲在內存中,如果想要永久存儲,則存儲到關系數據庫中。
網頁下載器( urllib )
將 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
?,則可以打印出獲取到的頁面。
構造 Request
上面的代碼,可以修改為:
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)
攜帶參數
新建 baidu 2. 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 。 打開 fiddler 之后,卻意外發現,上面的代碼會報錯504,無論是 baidu.py 還是 baidu 2. 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)
網頁解析器( BeautifulSoup )
從網頁中提取出有價值的數據和新的 url 列表。
解析器選擇
為了實現解析器,可以選擇使用正則表達式、 html.parser 、 BeautifulSoup 、 lxml 等,這里我們選擇 BeautifulSoup 。
其中,正則表達式基于模糊匹配,而另外三種則是基于 DOM 結構化解析。
BeautifulSoup
安裝測試
1、安裝,在命令行下執行?pip install beautifulsoup4
?。 2、測試
import bs4
print(bs4)
使用說明
基本用法
1、創建 BeautifulSoup 對象
import bs4
from bs4 import BeautifulSoup
# 根據html網頁字符串創建BeautifulSoup對象
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p ><b>The Dormouse's story</b></p>
<p >Once upon a time there were three little sisters; and their names were
<a >Elsie</a>,
<a >Lacie</a> and
<a >Tillie</a>;
and they lived at the bottom of a well.</p>
<p >...</p>
"""
soup = BeautifulSoup(html_doc)
print(soup.prettify())
2、訪問節點
print(soup.title)
print(soup.title.name)
print(soup.title.string)
print(soup.title.parent.name)
print(soup.p)
print(soup.p['class'])
3、指定 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'))
4、從文檔中找到所有?< a >
?標簽的鏈接
for link in soup.find_all('a'):
? ?print(link.get('href'))
出現了警告,根據提示,我們在創建 BeautifulSoup 對象時,指定解析器即可。
soup = BeautifulSoup(html_doc, 'html.parser')
5、從文檔中獲取所有文字內容
print(soup.get_text())
6、正則匹配
link_node = soup.find('a', href=re.compile(r"til"))
print(link_node)
后記
python 爬蟲基礎知識,至此足夠,接下來,在實戰中學習更高級的知識。
題圖:pexels,CC0 授權。
點擊閱讀原文,查看更多 Python 教程和資源。
閱讀原文:http://mp.weixin.qq.com/s?__biz=MzAwNDc0MTUxMw==&mid=2649639947&idx=1&sn=09780c2f4168aa1e7ba02e899d97d692&scene=0#wechat_redirect