python爬蟲(1)——基本知識和概念
python 基本語法
python 爬蟲的物件大部分都是文字,所以需要對python字串的用法熟悉。python中字串是由雙引號或者單引號中的字元組成。通常用到的字串操作有加法乘法、切片索引、格式化等
加法和乘法
字串的加法在python爬蟲中通常用於URL的構造
a = "hello" b = "world" print(a+b)# helloworld
python對字串的操作相對於傳統語言,不同之處在於包含一個乘法。格式為
字串*number
對應的乘數代表將字串複製此數字的份數a = "python" print(a*3)# pythonpythonpython
切片索引
字串的索引和切片是通過string[x]來獲取字串相關的資訊
a = "python" print(a[0]) # p print(a[-1])# n print(a[:2])# py
字串的索引從0開始,最後一個字元的索引也可以為-1。可以使用 : 來進切片操作。
a[:2]
不包括下標為2的元素字串方法
python 中字串除了上面的基本操作外,還提供了一系列的方法來增強其功能,方便開發者使用對其進行處理。
split()
split方法會將字串按照使用者指定的分隔符進行分割,生成一個列表a = "123-456-789" print(a.split("-"))# ['123', '456', '789']
可以看到通過呼叫split方法將字串按照指定的分隔符進行了切割。
當沒有指定分隔符時,程式會預設將所有的空格作為分隔符(空格、製表符、換行等等)
replace()
replace 函式其實本質上就是字串的查詢和替換,會替換使用者指定的字串到原有字串上a = "pythonlinux" print(a.replace("linux","C++"))#pythonC++
strip()
strip函式會將字串兩側的空格去除,但是不會影響中間的空格。a = " python \n" print(a.strip()) #python
format()
format經常用在python爬蟲中,我通常用來格式化URLprint("https://www.{}.com".format("baidu")) #https://www.baidu.com
python 爬蟲原理
對於計算機網路不熟練的我們,在學習爬蟲時,只需要知道基本的網路連線原理即可,計算機發送一個Request,伺服器返回一個Response。
那麼對於網路爬蟲來說,我們只需要模擬上述過程即可,即
- 構造訪問請求頭等資料,發起一個Request
- 解析伺服器端返回的Respone,提取對我們有用的資料
python 爬蟲第三方庫
對於爬蟲的初學者,主要掌握三大爬蟲庫,再在次基礎上深入研究,分別為Requests、BeautifulSoup、Lxml
Requests
Requests庫作用:請求網站獲取返回資料
import requests res = requests.get("https://www.baidu.com") print(res.text)
可以看到程式會返回指定網頁的html資料。有時候我們也需要在request請求中加入請求頭,以達到偽裝成瀏覽器的目的
import requests header = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36" } res = requests.get("https://www.baidu.com",headers = headers) print(res.text)
Request庫除了get方法,還有post()方法用於提交表單來爬取需要登入才能獲得資料的網站。
Request庫請求也可能會丟擲異常,使用者可以使用try/catch來進行抓取。常見的異常和錯誤為:ConnectionError、Timeout、TooManyRedirects
BeautifulSoup
BeautifulSoup是一個常用的模組,可以用其進行解析Request庫解析的網頁,並將其轉為soup文件,從而進一步處理
from bs4 import BeautifulSoup import requests res = requests.get("https://www.baidu.com") soup = BeautifulSoup(res.text,"html.parser") print(soup.prettify())
輸出為:
這裡可以看到通過呼叫soup的prettify函式,可以將html檔案格式化成html檔案。在生成soup文件的建構函式中,我使用了html.parser
這個HTML解析器之外,python還提供了其他一些解析器解析器 使用方法 優點 缺點 python標準庫 BeautifulSoup(html,”html.parser”) 內建標準、速度始終 容錯能力差 lxml HTML解析器 BeautifulSoup(html,”lxml”) 速度快 需裝C庫 lxml XML解析器 BeautifulSoup(html,”xml”) 速度快、唯一支援xml解析的庫 需裝C庫 html5lib解析器 BeautifulSoup(html,”html5lib”) 容錯性強、生成html5文件 速度比較慢 soup文件物件提供了幾個重要的方法來進行元素的定位。
find、find_all
soup.find_all("div","item1") # 檢視所有的class=item1的div標籤 soup.find_all("div",class="item1") soup.find_all("div",attrs={"class":"item1"})
對於更加具體的find_all引數,請檢視BeautifulSoup的文件
對於find函式,其實和find_all
差不多,但是find_all返回的是文件中符合條件的所有tag,是一個tag的集合,但是find方法返回的是一個tagselector
selector方法用於快速提取資訊,在可chrome瀏覽器控制檯中檢視selector來獲取某個元素的selector
import requests from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36" } res = requests.get("http://bj.xiaozhu.com/",headers = headers) soup = BeautifulSoup(res.text,"html.parser") price = soup.select("#page_list > ul > li:nth-of-type(1) > div.result_btm_con.lodgeunitname > span.result_price > i") print(price)
返回結果為:
[<i>5280</i>]
其中有一個nth-of-type(1)
,當去掉此處時,返回的就是價格的列表了,呼叫price.get_text()
即可
Lxml
基於libxml2此XML解析庫的python封裝,此模組是使用C語言編寫,解析速度比BeautifulSoup更快。