310
技術社區[雲棲]
Python爬蟲基礎
前言
Python非常適合用來開發網頁爬蟲,理由如下:
1、抓取網頁本身的接口
相比與其他靜態編程語言,如Java,c#,c++,python抓取網頁文檔的接口更簡潔;相比其他動態腳本語言,如perl,shell,python的urllib包提供了較為完整的訪問網頁文檔的API。(當然ruby也是很好的選擇)
此外,抓取網頁有時候需要模擬瀏覽器的行為,很多網站對於生硬的爬蟲抓取都是封殺的。這是我們需要模擬user agent的行為構造合適的請求,譬如模擬用戶登陸、模擬session/cookie的存儲和設置。在python裏都有非常優秀的第三方包幫你搞定,如Requests,mechanize
2、網頁抓取後的處理
抓取的網頁通常需要處理,比如過濾html標簽,提取文本等。python的beautifulsoap提供了簡潔的文檔處理功能,能用極短的代碼完成大部分文檔的處理。
其實以上功能很多語言和工具都能做,但是用python能夠幹得最快,最幹淨。如果你想學習Python可以來這個群,首先是四七二,中間是三零九,最後是二六一,裏麵有大量的學習資料可以下載。
Life is short, you need python.
PS:python2.x和python3.x有很大不同,本文隻討論python3.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存儲在內存中,如果想要永久存儲,則存儲到關係數據庫中。如果你想學習Python可以來這個群,首先是四七二,中間是三零九,最後是二六一,裏麵有大量的學習資料可以下載。
網頁下載器(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)
攜帶參數
新建baidu2.py,內容如下:
import urllib.request
import urllib.parse
url = 'https://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還是baidu2.py。
雖然python有報錯,但是在fiddler中,我們可以看到請求信息,確實攜帶了參數。
經過查找資料,發現python以前版本的Request都不支持代理環境下訪問https。但是,最近的版本應該支持了才對。那麼,最簡單的辦法,就是換一個使用http協議的url來爬取,比如,換成https://www.csdn.NET
。結果,依然報錯,隻不過變成了400錯誤。
然而,然而,然而。。。神轉折出現了!!!
當我把url換成https://www.csdn.Net/
後,請求成功!沒錯,就是在網址後麵多加了一個斜杠/
。同理,把https://www.baidu.com
改成https://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('https://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 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="https://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="https://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="https://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())
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爬蟲基礎知識,至此足夠,接下來,在實戰中學習更高級的知識。
最後更新:2017-05-08 10:01:37