您好,登錄后才能下訂單哦!
小編給大家分享一下常用網(wǎng)絡(luò)爬蟲模塊是什么,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
urllib模塊
urllib庫(kù)是python中自帶的模塊,也是一個(gè)最基本的網(wǎng)絡(luò)請(qǐng)求庫(kù),該模塊提供了一個(gè)urlopen()方法,通過(guò)該方法指定URL發(fā)送網(wǎng)絡(luò)請(qǐng)求來(lái)獲取數(shù)據(jù)。
urllib 是一個(gè)收集了多個(gè)涉及 URL 的模塊的包
urllib.request 打開(kāi)和讀取 URL
三行代碼即可爬取百度首頁(yè)源代碼:
import urllib.request # 打開(kāi)指定需要爬取的網(wǎng)頁(yè) response=urllib.request.urlopen('http://www.baidu.com') # 或者是 # from urllib import request # response = request.urlopen('http://www.baidu.com') # 打印網(wǎng)頁(yè)源代碼 print(response.read().decode())
加入decode()是為了避免出現(xiàn)下圖中十六進(jìn)制內(nèi)容
加入decode()進(jìn)行解碼后
下面三種本篇將不做詳述
urllib.error 包含 urllib.request 拋出的異常
urllib.parse 用于解析 URL
urllib.robotparser 用于解析 robots.txt 文件
requests模塊
requests模塊是python中實(shí)現(xiàn)HTTP請(qǐng)求的一種方式,是第三方模塊,該模塊在實(shí)現(xiàn)HTTP請(qǐng)求時(shí)要比urllib模塊簡(jiǎn)化很多,操作更加人性化。
以GET請(qǐng)求為例:
import requests response = requests.get('http://www.baidu.com/') print('狀態(tài)碼:', response.status_code) print('請(qǐng)求地址:', response.url) print('頭部信息:', response.headers) print('cookie信息:', response.cookies) # print('文本源碼:', response.text) # print('字節(jié)流源碼:', response.content)
輸出結(jié)果如下:
狀態(tài)碼: 200 請(qǐng)求地址: http://www.baidu.com/ 頭部信息: {'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Sun, 10 May 2020 02:43:33 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:23 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'} cookie信息: <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
這里講解一下response.text和 response.content的區(qū)別:
response.content是直接從網(wǎng)絡(luò)上面抓取的數(shù)據(jù),沒(méi)有經(jīng)過(guò)任何解碼,所以是一個(gè) bytes類型
response.text是將response.content進(jìn)行解碼的字符串,解碼需要指定一個(gè)編碼方式, requests會(huì)根據(jù)自己的猜測(cè)來(lái)判斷編碼的方式,所以有時(shí)候可能會(huì)猜測(cè)錯(cuò)誤,就會(huì)導(dǎo)致解碼產(chǎn)生亂碼,這時(shí)候就應(yīng)該使用 response.content.decode(‘utf-8’)
進(jìn)行手動(dòng)解碼
以POST請(qǐng)求為例
import requests data={'word':'hello'} response = requests.post('http://www.baidu.com',data=data) print(response.content)
請(qǐng)求headers處理
當(dāng)爬取頁(yè)面由于該網(wǎng)頁(yè)為防止惡意采集信息而使用反爬蟲設(shè)置,從而拒絕用戶訪問(wèn),我們可以通過(guò)模擬瀏覽器的頭部信息來(lái)進(jìn)行訪問(wèn),這樣就能解決反爬蟲設(shè)置的問(wèn)題。
通過(guò)瀏覽器進(jìn)入指定網(wǎng)頁(yè),右擊鼠標(biāo),選中“檢查”,選擇“Network”,刷新頁(yè)面后選擇第一條信息,右側(cè)消息頭面板將顯示下圖中請(qǐng)求頭部信息
例如:
import requests url = 'https://www.bilibili.com/' headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'} response = requests.get(url, headers=headers) print(response.content.decode())
網(wǎng)絡(luò)超時(shí)
在訪問(wèn)一個(gè)頁(yè)面,如果該頁(yè)面長(zhǎng)時(shí)間未響應(yīng),系統(tǒng)就會(huì)判斷該網(wǎng)頁(yè)超時(shí),所以無(wú)法打開(kāi)網(wǎng)頁(yè)。
例如:
import requests url = 'http://www.baidu.com' # 循環(huán)發(fā)送請(qǐng)求50次 for a in range(0, 50): try: # timeout數(shù)值可根據(jù)用戶當(dāng)前網(wǎng)速,自行設(shè)置 response = requests.get(url, timeout=0.03) # 設(shè)置超時(shí)為0.03 print(response.status_code) except Exception as e: print('異常'+str(e)) # 打印異常信息
部分輸出結(jié)果如下:
代理服務(wù)
設(shè)置代理IP可以解決不久前可以爬取的網(wǎng)頁(yè)現(xiàn)在無(wú)法爬取了,然后報(bào)錯(cuò)——由于連接方在一段時(shí)間后沒(méi)有正確答復(fù)或連接的主機(jī)沒(méi)有反應(yīng),連接嘗試失敗的問(wèn)題。
以下網(wǎng)站可以提供免費(fèi)代理IP https://www.xicidaili.com/
例如:
import requests # 設(shè)置代理IP proxy = {'http': '117.45.139.139:9006', 'https': '121.36.210.88:8080' } # 發(fā)送請(qǐng)求 url = 'https://www.baidu.com' response = requests.get(url, proxies=proxy) # 也就是說(shuō)如果想取文本數(shù)據(jù)可以通過(guò)response.text # 如果想取圖片,文件,則可以通過(guò) response.content # 以字節(jié)流的形式打印網(wǎng)頁(yè)源代碼,bytes類型 print(response.content.decode()) # 以文本的形式打印網(wǎng)頁(yè)源代碼,為str類型 print(response.text) # 默認(rèn)”iso-8859-1”編碼,服務(wù)器不指定的話是根據(jù)網(wǎng)頁(yè)的響應(yīng)來(lái)猜測(cè)編碼。
Beautiful Soup模塊
Beautiful Soup模塊是一個(gè)用于HTML和XML文件中提取數(shù)據(jù)的python庫(kù)。Beautiful Soup模塊自動(dòng)將輸入的文檔轉(zhuǎn)換為Unicode編碼,輸出文檔轉(zhuǎn)換為UTF-8編碼,你不需要考慮編碼方式,除非文檔沒(méi)有指定一個(gè)編碼方式,這時(shí),Beautiful Soup就不能自動(dòng)識(shí)別編碼方式了,然后,僅僅需要說(shuō)明一下原始編碼方式就可以了。
例如:
from bs4 import 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> """ # 創(chuàng)建對(duì)象 soup = BeautifulSoup(html_doc, features='lxml') # 或者創(chuàng)建對(duì)象打開(kāi)需要解析的html文件 # soup = BeautifulSoup(open('index.html'), features='lxml') print('源代碼為:', soup)# 打印解析的HTML代碼
運(yùn)行結(jié)果如下:
<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 class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a> and <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> </body></html>
用Beautiful Soup爬取百度首頁(yè)標(biāo)題
from bs4 import BeautifulSoup import requests response = requests.get('http://news.baidu.com') soup = BeautifulSoup(response.text, features='lxml') print(soup.find('title').text)
運(yùn)行結(jié)果如下:
百度新聞——海量中文資訊平臺(tái)
看完了這篇文章,相信你對(duì)常用網(wǎng)絡(luò)爬蟲模塊是什么有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。