本篇文章主要介紹了python3使用requests模組爬取頁面內容的實戰演練,具有一定的參考價值,有興趣的可以了解一下
1.安裝pip
#我的個人桌面系統用的linuxmint,系統預設沒有安裝pip,考慮到後面安裝requests模組使用pip,所以我在這裡第一步先安裝pip。
$ sudo apt install python-pip
安裝成功,查看PIP版本:
$ pip -V
2.安裝requests模組
#這裡我是透過pip方式進行安裝:
$ pip install requests
運行import requests,如果沒提示錯誤,那說明已經安裝成功了!
檢定是否安裝成功
3.安裝beautifulsoup4
Beautiful Soup 是可以從HTML或XML文件中提取資料的Python庫。它能夠透過你喜歡的轉換器實現慣用的文檔導航,尋找、修改文件的方式。 Beautiful Soup會幫你節省數小時甚至數天的工作時間。
$ sudo apt-get install python3-bs4
註:這裡我使用的是python3的安裝方式,如果你用的是python2,可以使用下面指令安裝。
$ sudo pip install beautifulsoup4
4.requests模組淺析
1)發送請求
首先當然要導入Requests模組:
>>> import requests
然後,取得目標抓取網頁。這裡我以下為例:
>>> r = requests.get('http://www.jb51.net/article/124421.htm')
這裡回傳一個名為 r 的回應物件。我們可以從這個物件中獲取所有我們想要的資訊。這裡的get是http的回應方法,所以舉一反三你也可以將其替換為put、delete、post、head。
2)傳遞URL參數
有時我們想為 URL 的查詢字串傳遞某種資料。如果你是手工建立 URL,那麼資料會以鍵/值對的形式置於 URL 中,跟在一個問號的後面。例如, cnblogs.com/get?key=val。 Requests 允許你使用 params 關鍵字參數,以一個字串字典來提供這些參數。
舉例來說,當我們google搜尋「python爬蟲」關鍵字時,newwindow(新視窗開啟)、q及oq(搜尋關鍵字)等參數可以手工組成URL ,那麼你可以使用以下程式碼:
>>> payload = {'newwindow': '1', 'q': 'python爬虫', 'oq': 'python爬虫'} >>> r = requests.get("https://www.google.com/search", params=payload)
3)回應內容
透過r.text或r.content來取得頁面回應內容。
>>> import requests >>> r = requests.get('https://github.com/timeline.json') >>> r.text
Requests 會自動解碼來自伺服器的內容。大多數 unicode 字元集都能無縫解碼。這裡補充一點r.text和r.content二者的差別,簡單說:
resp.text回傳的是Unicode型的資料;
resp.content回傳的是bytes型也就是二進制的資料;
所以如果你想取文本,可以透過r.text,如果想取圖片,文件,則可以透過r.content。
4)取得網頁編碼
>>> r = requests.get('http://www.cnblogs.com/') >>> r.encoding 'utf-8'
5)取得回應狀態碼
#我們可以偵測回應狀態碼:
>>> r = requests.get('http://www.cnblogs.com/') >>> r.status_code 200
5.案例示範
最近公司剛引進了一個OA系統,這裡我以其官方說明文件頁面為例,並且只抓取頁面中文章標題和內容等有用資訊。
示範環境
作業系統:linuxmint
python版本:python 3.5.2
使用模組:requests、beautifulsoup4
#程式碼如下:
#!/usr/bin/env python # -*- coding: utf-8 -*- _author_ = 'GavinHsueh' import requests import bs4 #要抓取的目标页码地址 url = 'http://www.ranzhi.org/book/ranzhi/about-ranzhi-4.html' #抓取页码内容,返回响应对象 response = requests.get(url) #查看响应状态码 status_code = response.status_code #使用BeautifulSoup解析代码,并锁定页码指定标签内容 content = bs4.BeautifulSoup(response.content.decode("utf-8"), "lxml") element = content.find_all(id='book') print(status_code) print(element)
程式運行返回爬去結果:
抓取成功
關於爬去結果亂碼問題
其實起初我是直接用的系統默認自帶的python2操作的,但在抓取返回內容的編碼亂碼問題上折騰了老半天,google了多種解決方案都無效。在被python2「整瘋「之後,只好老實實用python3了。對於python2的爬取頁面內容亂碼問題,歡迎各位前輩們分享經驗,以幫助我等後生少走彎路。
後記
python的爬蟲相關模組有很多,除了requests模組,再如urllib和pycurl以及tornado等。相較而言,我個人覺得requests模組是相對簡單易上手的了。透過文本,大家可以迅速學會使用python的requests模組爬取頁碼內容。本人能力有限,如果文章有任何錯誤歡迎不吝賜教,其次如果大家有任何關於python爬去頁面內容的疑難雜問,也歡迎和大家一起交流討論。
以上是實例詳解python3使用requests模組爬取頁面內容的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。

toAccesselementsInapythonlist,useIndIndexing,負索引,切片,口頭化。 1)indexingStartSat0.2)否定indexingAccessesessessessesfomtheend.3)slicingextractsportions.4)iterationerationUsistorationUsisturessoreTionsforloopsoreNumeratorseforeporloopsorenumerate.alwaysCheckListListListListlentePtotoVoidToavoIndexIndexIndexIndexIndexIndExerror。

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

禪工作室 13.0.1
強大的PHP整合開發環境

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

記事本++7.3.1
好用且免費的程式碼編輯器