1. 程式人生 > 程式設計 >10個python爬蟲入門基礎程式碼例項 + 1個簡單的python爬蟲完整例項

10個python爬蟲入門基礎程式碼例項 + 1個簡單的python爬蟲完整例項

本文主要涉及python爬蟲知識點:

web是如何互動的

requests庫的get、post函式的應用

response物件的相關函式,屬性

python檔案的開啟,儲存

程式碼中給出了註釋,並且可以直接執行哦

如何安裝requests庫(安裝好python的朋友可以直接參考,沒有的,建議先裝一哈python環境)

windows使用者,Linux使用者幾乎一樣:

開啟cmd輸入以下命令即可,如果python的環境在C盤的目錄,會提示許可權不夠,只需以管理員方式執行cmd視窗

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests

Linux使用者類似(ubantu為例): 許可權不夠的話在命令前加入sudo即可

sudo pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests

python爬蟲入門基礎程式碼例項如下

1.Requests爬取BD頁面並列印頁面資訊

# 第一個爬蟲示例,爬取百度頁面
import requests #匯入爬蟲的庫,不然調用不了爬蟲的函式
response = requests.get("http://www.baidu.com") #生成一個response物件
response.encoding = response.apparent_encoding #設定編碼格式
print("狀態碼:"+ str( response.status_code ) ) #列印狀態碼
print(response.text)#輸出爬取的資訊

2.Requests常用方法之get方法例項,下面還有傳參例項

# 第二個get方法例項
import requests #先匯入爬蟲的庫,不然調用不了爬蟲的函式
response = requests.get("http://httpbin.org/get") #get方法
print( response.status_code ) #狀態碼
print( response.text )

3. Requests常用方法之post方法例項,下面還有傳參例項

# 第三個 post方法例項
import requests #先匯入爬蟲的庫,不然調用不了爬蟲的函式
response = requests.post("http://httpbin.org/post") #post方法訪問
print( response.status_code ) #狀態碼
print( response.text )

4. Requests put方法例項

# 第四個 put方法例項
import requests #先匯入爬蟲的庫,不然調用不了爬蟲的函式
response = requests.put("http://httpbin.org/put") # put方法訪問
print( response.status_code ) #狀態碼
print( response.text )

5.Requests常用方法之get方法傳參例項(1)

如果需要傳多個引數只需要用&符號連線即可如下

# 第五個 get傳參方法例項
import requests #先匯入爬蟲的庫,不然調用不了爬蟲的函式
response = requests.get("http://httpbin.org/get?name=hezhi&age=20") # get傳參
print( response.status_code ) #狀態碼
print( response.text )

6.Requests常用方法之get方法傳參例項(2)

params用字典可以傳多個

# 第六個 get傳參方法例項
import requests #先匯入爬蟲的庫,不然調用不了爬蟲的函式
data = {
	"name":"hezhi","age":20
}
response = requests.get( "http://httpbin.org/get",params=data ) # get傳參
print( response.status_code ) #狀態碼
print( response.text )

7.Requests常用方法之post方法傳參例項(2) 和上一個有沒有很像

# 第七個 post傳參方法例項
import requests #先匯入爬蟲的庫,不然調用不了爬蟲的函式
data = {
	"name":"hezhi","age":20
}
response = requests.post( "http://httpbin.org/post",params=data ) # post傳參
print( response.status_code ) #狀態碼
print( response.text )

8.關於繞過反爬機制,以知呼為例

# 第好幾個方法例項
import requests #先匯入爬蟲的庫,不然調用不了爬蟲的函式
response = requests.get( "http://www.zhihu.com") #第一次訪問知乎,不設定頭部資訊
print( "第一次,不設頭部資訊,狀態碼:"+response.status_code )# 沒寫headers,不能正常爬取,狀態碼不是 200
#下面是可以正常爬取的區別,更改了User-Agent欄位
headers = {
		"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/80.0.3987.122 Safari/537.36"
}#設定頭部資訊,偽裝瀏覽器
response = requests.get( "http://www.zhihu.com",headers=headers ) #get方法訪問,傳入headers引數,
print( response.status_code ) # 200!訪問成功的狀態碼
print( response.text )

9.爬取資訊並儲存到本地

因為目錄關係,在D盤建立了一個叫做爬蟲的資料夾,然後儲存資訊

注意檔案儲存時的encoding設定

# 爬取一個html並儲存
import requests
url = "http://www.baidu.com"
response = requests.get( url )
response.encoding = "utf-8" #設定接收編碼格式
print("\nr的型別" + str( type(response) ) )
print("\n狀態碼是:" + str( response.status_code ) )
print("\n頭部資訊:" + str( response.headers ) )
print( "\n響應內容:" )
print( response.text )

#儲存檔案
file = open("D:\\爬蟲\\baidu.html","w",encoding="utf") #開啟一個檔案,w是檔案不存在則新建一個檔案,這裡不用wb是因為不用儲存成二進位制
file.write( response.text )
file.close()

10.爬取圖片,儲存到本地

#儲存百度圖片到本地
import requests #先匯入爬蟲的庫,不然調用不了爬蟲的函式
response = requests.get("https://www.baidu.com/img/baidu_jgylogo3.gif") #get方法的到圖片響應
file = open("D:\\爬蟲\\baidu_logo.gif","wb") #開啟一個檔案,wb表示以二進位制格式開啟一個檔案只用於寫入
file.write(response.content) #寫入檔案
file.close()#關閉操作,執行完畢後去你的目錄看一眼有沒有儲存成功

下面是一個完整的python爬蟲例項,功能是爬取百度貼吧上的圖片並下載到本地;

你也可以關注公眾號 Python客棧 回覆 756 獲取完整程式碼;

10個python爬蟲入門基礎程式碼例項 + 1個簡單的python爬蟲完整例項
掃描上面二維碼關注公眾號 Python客棧 回覆 756 獲取完整python爬蟲原始碼

python爬蟲主要操作步驟:

獲取網頁html文字內容;

分析html中圖片的html標籤特徵,用正則解析出所有的圖片url連結列表;

根據圖片的url連結列表將圖片下載到本地資料夾中。

1. urllib+re實現

#!/usr/bin/python
# coding:utf-8
# 實現一個簡單的爬蟲,爬取百度貼吧圖片
import urllib
import re

# 根據url獲取網頁html內容
def getHtmlContent(url):
  page = urllib.urlopen(url)
  return page.read()

# 從html中解析出所有jpg圖片的url
# 百度貼吧html中jpg圖片的url格式為:<img ... src="XXX.jpg" width=...>
def getJPGs(html):
  # 解析jpg圖片url的正則
  jpgReg = re.compile(r'<img.+?src="(.+?\.jpg)" width') # 注:這裡最後加一個'width'是為了提高匹配精確度
  # 解析出jpg的url列表
  jpgs = re.findall(jpgReg,html)
  
  return jpgs

# 用圖片url下載圖片並儲存成制定檔名
def downloadJPG(imgUrl,fileName):
  urllib.urlretrieve(imgUrl,fileName)
  
# 批量下載圖片,預設儲存到當前目錄下
def batchDownloadJPGs(imgUrls,path = './'):
  # 用於給圖片命名
  count = 1
  for url in imgUrls:
    downloadJPG(url,''.join([path,'{0}.jpg'.format(count)]))
    count = count + 1

# 封裝:從百度貼吧網頁下載圖片
def download(url):
  html = getHtmlContent(url)
  jpgs = getJPGs(html)
  batchDownloadJPGs(jpgs)
  
def main():
  url = 'http://tieba.baidu.com/p/2256306796'
  download(url)
  
if __name__ == '__main__':
  main()

執行上面指令碼,過幾秒種之後完成下載,可以在當前目錄下看到圖片已經下載好了:

10個python爬蟲入門基礎程式碼例項 + 1個簡單的python爬蟲完整例項

2. requests + re實現

下面用requests庫實現下載,把getHtmlContent和downloadJPG函式都用requests重新實現。

#!/usr/bin/python
# coding:utf-8
# 實現一個簡單的爬蟲,爬取百度貼吧圖片
import requests
import re

# 根據url獲取網頁html內容
def getHtmlContent(url):
  page = requests.get(url)
  return page.text

# 從html中解析出所有jpg圖片的url
# 百度貼吧html中jpg圖片的url格式為:<img ... src="XXX.jpg" width=...>
def getJPGs(html):
  # 解析jpg圖片url的正則
  jpgReg = re.compile(r'<img.+?src="(.+?\.jpg)" width') # 注:這裡最後加一個'width'是為了提高匹配精確度
  # 解析出jpg的url列表
  jpgs = re.findall(jpgReg,fileName):
  # 可自動關閉請求和響應的模組
  from contextlib import closing
  with closing(requests.get(imgUrl,stream = True)) as resp:
    with open(fileName,'wb') as f:
      for chunk in resp.iter_content(128):
        f.write(chunk)
  
# 批量下載圖片,預設儲存到當前目錄下
def batchDownloadJPGs(imgUrls,'{0}.jpg'.format(count)]))
    print '下載完成第{0}張圖片'.format(count)
    count = count + 1

# 封裝:從百度貼吧網頁下載圖片
def download(url):
  html = getHtmlContent(url)
  jpgs = getJPGs(html)
  batchDownloadJPGs(jpgs)
  
def main():
  url = 'http://tieba.baidu.com/p/2256306796'
  download(url)
  
if __name__ == '__main__':
  main()

上面介紹的10個python爬蟲入門基礎程式碼例項和1個簡單的python爬蟲完整例項雖然都是基礎知識但python爬蟲的主要操作方法也是這些,掌握這些python爬蟲就學會一大半了。更多關於python爬蟲的文章請檢視下面的相關羅拉