Python爬蟲常用庫總結:requests、beautifulsoup、selenium、xpath【生長吧!Python】
Python爬蟲常用庫總結:requests、beautifulsoup、selenium、xpath總結
大家好,我是北山啦,今天帶來的是在學習過程中的Python爬蟲常用庫,當然學無止境,這些只是爬蟲的基礎,更多姿勢需要你自己去探索呦
requests
requests基礎
requests模塊發送get請求
response響應對象
response.text 和response.content的區別
解決中文亂碼
response響應對象的其它常用屬性或方法
requests實操
requests模塊發送請求
發送帶參數的請求
超時參數timeout的使用
requests發送post請求的方法
BeautifulSoup
常見解釋器的優缺點
常用操作
幾個簡單的瀏覽結構化數據的方法
從文檔中找到所有的< a>標簽的鏈接
在文檔中獲取所有的文字內容
通過標簽和屬性獲取
Name屬性
多個屬性
多值屬性
可以遍歷的字符串
注釋及特殊字符串
遍歷文檔樹
子節點
find_all方法
.contents和.children
selenium
selenium介紹
chrome瀏覽器的運行效果
phantomjs無界面瀏覽器的運行效果
selenium的作用和工作原理
selenium的安裝以及簡單使用
selenium的簡單使用
lxml
利用xpath獲取text或者href內容
xpath的語法
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple 包名
官方網址:
Requests: 讓 HTTP 服務人類
Beautiful Soup 4.4.0 文檔
Selenium官網
lxml - XML and HTML with Python
requests
requests官方文檔 https://docs.python-requests.org/zh_CN/latest/
進行爬蟲,首先要對網址進行請求,這個時候就要用刀我們的requests模塊了。requests是python的一個HTTP客戶端庫,跟urllib,urllib2類似。與urllib,urllib2相比,requests模塊語法更加簡單。正如他的官網所說:
requests模塊介紹
發送http請求,獲取響應數據
requests模塊是一個第三方模塊,需要在你的python(虛擬)環境中額外安裝
pip/pip3 install requests
requests基礎
requests模塊發送get請求
import requests # 目標url url = 'https://www.baidu.com' # 向目標url發送get請求 response = requests.get(url) # 打印響應內容 print(response.text)
response響應對象
觀察上邊代碼運行結果發現,有好多亂碼;這是因為編解碼使用的字符集不同早造成的;我們嘗試使用下邊的辦法來解決中文亂碼問題
import requests url = 'https://www.baidu.com' # 向目標url發送get請求 response = requests.get(url) # 打印響應內容 # print(response.text) print(response.content.decode()) # 注意這里!
response.text是requests模塊按照chardet模塊推測出的編碼字符集進行解碼的結果
網絡傳輸的字符串都是bytes類型的,所以response.text = response.content.decode(‘推測出的編碼字符集’)
我們可以在網頁源碼中搜索charset,嘗試參考該編碼字符集,注意存在不準確的情況
response.text 和response.content的區別
==response.text==
類型:str
解碼類型: requests模塊自動根據HTTP 頭部對響應的編碼作出有根據的推測,推測的文本編碼
==response.content==
類型:bytes
解碼類型: 沒有指定
解決中文亂碼
通過對response.content進行decode,來解決中文亂碼
response.content.decode() 默認utf-8
response.content.decode("GBK")
常見的編碼字符集
utf-8
gbk
gb2312
ascii (讀音:阿斯克碼)
iso-8859-1
response響應對象的其它常用屬性或方法
# 1.2.3-response其它常用屬性 import requests # 目標url url = 'https://www.baidu.com' # 向目標url發送get請求 response = requests.get(url) # 打印響應內容 # print(response.text) # print(response.content.decode()) # 注意這里! print(response.url) # 打印響應的url print(response.status_code) # 打印響應的狀態碼 print(response.request.headers) # 打印響應對象的請求頭 print(response.headers) # 打印響應頭 print(response.request._cookies) # 打印請求攜帶的cookies print(response.cookies) # 打印響應中攜帶的cookies
requests實操
requests模塊發送請求
發送帶header的請求
我們先寫一個獲取百度首頁的代碼
import requests url = 'https://www.baidu.com' response = requests.get(url) print(response.content.decode()) # 打印響應對應請求的請求頭信息 print(response.request.headers)
從瀏覽器中復制User-Agent,構造headers字典;完成下面的代碼后,運行代碼查看結果
import requests url = 'https://www.baidu.com' headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"} # 在請求頭中帶上User-Agent,模擬瀏覽器發送請求 response = requests.get(url, headers=headers) print(response.content) # 打印請求頭信息 print(response.request.headers)
發送帶參數的請求
我們在使用百度搜索的時候經常發現url地址中會有一個 ?,那么該問號后邊的就是請求參數,又叫做查詢字符串
在url攜帶參數,直接對含有參數的url發起請求
import requests headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"} url = 'https://www.baidu.com/s?wd=python' response = requests.get(url, headers=headers)
通過params攜帶參數字典
1.構建請求參數字典
2.向接口發送請求的時候帶上參數字典,參數字典設置給params
import requests headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"} # 這是目標url # url = 'https://www.baidu.com/s?wd=python' # 最后有沒有問號結果都一樣 url = 'https://www.baidu.com/s?' # 請求參數是一個字典 即wd=python kw = {'wd': 'python'} # 帶上請求參數發起請求,獲取響應 response = requests.get(url, headers=headers, params=kw) print(response.content)
從瀏覽器中復制User-Agent和Cookie
瀏覽器中的請求頭字段和值與headers參數中必須一致
headers請求參數字典中的Cookie鍵對應的值是字符串
import requests url = 'https://github.com/USER_NAME' # 構造請求頭字典 headers = { # 從瀏覽器中復制過來的User-Agent 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36', # 從瀏覽器中復制過來的Cookie 'Cookie': 'xxx這里是復制過來的cookie字符串' } # 請求頭參數字典中攜帶cookie字符串 resp = requests.get(url, headers=headers) print(resp.text)
超時參數timeout的使用
在平時網上沖浪的過程中,我們經常會遇到網絡波動,這個時候,一個請求等了很久可能任然沒有結果。
在爬蟲中,一個請求很久沒有結果,就會讓整個項目的效率變得非常低,這個時候我們就需要對請求進行強制要求,讓他必須在特定的時間內返回結果,否則就報錯。
超時參數timeout的使用方法
response = requests.get(url, timeout=3)
timeout=3表示:發送請求后,3秒鐘內返回響應,否則就拋出異常
import requests url = 'https://twitter.com' response = requests.get(url, timeout=3) # 設置超時時間
requests發送post請求的方法
response = requests.post(url, data)
data參數接收一個字典
requests模塊發送post請求函數的其它參數和發送get請求的參數完全一致
BeautifulSoup
BeautifulSoup官方文檔 https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/
Beautiful Soup 是一個可以從HTML或XML文件中提取數據的Python庫.它能夠通過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式.Beautiful Soup會幫你節省數小時甚至數天的工作時間.
@[toc]
常見解釋器的優缺點
常用操作
安裝方法
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple beautifulsoup4
導入即可
from bs4 import BeautifulSoup
html_doc = """
The Dormouse's story
Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well.
...
"""soup = BeautifulSoup(html_doc,"lxml")
幾個簡單的瀏覽結構化數據的方法
soup.title
soup.title.name
'title'
soup.title.string
"The Dormouse's story"
soup.title.text
"The Dormouse's story"
soup.title.parent.name
'head'
soup.p
The Dormouse's story
soup.p.name
'p'
soup.p["class"]
['title']
soup.a
soup.find("a")
soup.find_all("a")
從文檔中找到所有的< a>標簽的鏈接
for link in soup.find_all("a"): print(link.get("href"))
http://example.com/elsie http://example.com/lacie http://example.com/tillie
在文檔中獲取所有的文字內容
print(soup.get_text())
The Dormouse's story The Dormouse's story Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well. ...
通過標簽和屬性獲取
Tag有很多方法和屬性,在 遍歷文檔樹 和 搜索文檔樹 中有詳細解釋.現在介紹一下tag中最重要的屬性: name和attributes
soup = BeautifulSoup('Extremely bold') tag = soup.b tag
Extremely bold
type(tag)
bs4.element.Tag
Name屬性
每個tag都有自己的名字,通過 .name 來獲取:
tag.name
'b'
如果改變了tag的name,那將影響所有通過當前Beautiful Soup對象生成的HTML文檔
tag.name = "blockquote" tag
Extremely bold
多個屬性
一個tag可能有很多個屬性.tag 有一個 “class” 的屬性,值為 “boldest” . tag的屬性的操作方法與字典相同:
tag["class"]
['boldest']
tag.attrs
{'class': ['boldest']}
tag的屬性可以被添加,刪除或修改. 再說一次, tag的屬性操作方法與字典一樣
tag["class"] = "verybold" tag["id"] = 1 tag
Extremely bold
del tag["class"] tag
Extremely bold
多值屬性
css_soup = BeautifulSoup('
') css_soup.p['class']['body', 'strikeout']
css_soup = BeautifulSoup('
') css_soup.p['class']['body']
可以遍歷的字符串
字符串常被包含在tag內.Beautiful Soup用 NavigableString 類來包裝tag中的字符串:
tag.string
'Extremely bold'
type(tag.string)
bs4.element.NavigableString
一個 NavigableString 字符串與Python中的Unicode字符串相同,
并且還支持包含在遍歷文檔樹 和 搜索文檔樹 中的一些特性.
通過 unicode() 方法可以直接將 NavigableString 對象轉換成Unicode字符串:
tag中包含的字符串不能編輯,但是可以被替換成其他的字符串,用replace_with()方法
tag.string.replace_with("No longer bold") tag
No longer bold
注釋及特殊字符串
文檔的注釋部分
markup = "" soup = BeautifulSoup(markup) comment = soup.b.string comment
'Hey, buddy. Want to buy a used parser?'
type(comment)
bs4.element.Comment
Comment 對象是一個特殊類型的 NavigableString 對象:
comment
'Hey, buddy. Want to buy a used parser?'
但是當它出現在HTML文檔中時, Comment 對象會使用特殊的格式輸出:
print(soup.prettify())
from bs4 import CData cdata = CData("A CDATA block") comment.replace_with(cdata) print(soup.b.prettify())
遍歷文檔樹
html_doc = """
The Dormouse's story
Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well.
...
"""from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc,"html.parser")
子節點
一個Tag可能包含多個字符串或其它的Tag,這些都是這個Tag的子節點.Beautiful Soup提供了許多操作和遍歷子節點的屬性.
soup.head
soup.title
這是個獲取tag的小竅門,可以在文檔樹的tag中多次調用這個方法.下面的代碼可以獲取
標簽中的第一個標簽:soup.body.b
The Dormouse's story
通過點取屬性的方式只能獲得當前名字的第一個tag:
soup.a
find_all方法
如果想要得到所有的標簽,或是通過名字得到比一個tag更多的內容的時候,就需要用到 Searching the tree 中描述的方法,比如: find_all()
soup.find_all("a")
.contents和.children
head_tag = soup.head head_tag
head_tag.contents
[
head_tag.contents[0]
head_tag.contents[0].contents
["The Dormouse's story"]
selenium
selenium官方文檔 https://www.selenium.dev/selenium/docs/api/py/api.html
selenium介紹
chrome瀏覽器的運行效果
在下載好chromedriver以及安裝好selenium模塊后,執行下列代碼并觀察運行的過程
from selenium import webdriver # 如果driver沒有添加到了環境變量,則需要將driver的絕對路徑賦值給executable_path參數 # driver = webdriver.Chrome(executable_path='/home/worker/Desktop/driver/chromedriver') # 如果driver添加了環境變量則不需要設置executable_path driver = webdriver.Chrome() # 向一個url發起請求 driver.get("http://www.itcast.cn/") # 把網頁保存為圖片,69版本以上的谷歌瀏覽器將無法使用截圖功能 # driver.save_screenshot("itcast.png") print(driver.title) # 打印頁面的標題 # 退出模擬瀏覽器 driver.quit() # 一定要退出!不退出會有殘留進程!
phantomjs無界面瀏覽器的運行效果
PhantomJS 是一個基于Webkit的“無界面”(headless)瀏覽器,它會把網站加載到內存并執行頁面上的 JavaScript。-:http://phantomjs.org/download.html
from selenium import webdriver # 指定driver的絕對路徑 driver = webdriver.PhantomJS(executable_path='/home/worker/Desktop/driver/phantomjs') # driver = webdriver.Chrome(executable_path='/home/worker/Desktop/driver/chromedriver') # 向一個url發起請求 driver.get("http://www.itcast.cn/") # 把網頁保存為圖片 driver.save_screenshot("itcast.png") # 退出模擬瀏覽器 driver.quit() # 一定要退出!不退出會有殘留進程!
無頭瀏覽器與有頭瀏覽器的使用場景
通常在開發過程中我們需要查看運行過程中的各種情況所以通常使用有頭瀏覽器
在項目完成進行部署的時候,通常平臺采用的系統都是服務器版的操作系統,服務器版的操作系統必須使用無頭瀏覽器才能正常運行
selenium的作用和工作原理
利用瀏覽器原生的API,封裝成一套更加面向對象的Selenium WebDriver API,直接操作瀏覽器頁面里的元素,甚至操作瀏覽器本身(截屏,窗口大小,啟動,關閉,安裝插件,配置證書之類的)
selenium的安裝以及簡單使用
以edge瀏覽器為例 參見這個blog哦,驅動chrome瀏覽器同理
selenium驅動edge瀏覽器
chromedriver環境的配置
windows環境下需要將 chromedriver.exe 所在的目錄設置為path環境變量中的路徑
linux/mac環境下,將 chromedriver 所在的目錄設置到系統的PATH環境值中
selenium的簡單使用
接下來我們就通過代碼來模擬百度搜索
import time from selenium import webdriver # 通過指定chromedriver的路徑來實例化driver對象,chromedriver放在當前目錄。 # driver = webdriver.Chrome(executable_path='./chromedriver') # chromedriver已經添加環境變量 driver = webdriver.Chrome() # 控制瀏覽器訪問url地址 driver.get("https://www.baidu.com/") # 在百度搜索框中搜索'python' driver.find_element_by_id('kw').send_keys('python') # 點擊'百度搜索' driver.find_element_by_id('su').click() time.sleep(6) # 退出瀏覽器 driver.quit()
webdriver.Chrome(executable_path='./chromedriver')中executable參數指定的是下載好的chromedriver文件的路徑
driver.find_element_by_id('kw').send_keys('python')定位id屬性值是’kw’的標簽,并向其中輸入字符串’python’
driver.find_element_by_id('su').click()定位id屬性值是su的標簽,并點擊
click函數作用是:觸發標簽的js的click事件
值是’kw’的標簽,并向其中輸入字符串’python’
driver.find_element_by_id('su').click()定位id屬性值是su的標簽,并點擊
click函數作用是:觸發標簽的js的click事件
使用xpath來提取數據,爬取數據的簡單語法。
lxml
requests官方文檔 https://lxml.de/
快速下載模塊
pip install lxml
導入模塊
from lxml import etree
利用xpath獲取text或者href內容
/li/a/@href 這樣取的應該是href的內容 /li/a/text() 這樣取得是text內容
xpath的語法
符號
XPath 使用路徑表達式在 XML 文檔中選取節點。節點是通過沿著路徑或者 step 來選取的。
實例
到這里就結束了,如果對你有幫助你。當然學無止境,這些只是爬蟲的基礎,更多姿勢需要你自己去探索呦
HTTP Python Selenium
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。