requests (第三方庫)基於urllib3 使用更加方便
阿新 • • 發佈:2018-12-19
#!/usr/bin/env python # -*- coding: utf-8 -*- # requests 是一個用python語言寫的第三方庫,在使用的時候,需要手動安裝(pip install requests) # 非常好用,基於urllib3 import requests ''' requests 請求的函式 # requests.Request # requests.request(method, url, **kwargs) # requests.get(url, params, **kwargs) # requests.post(url, data, json, **kwargs) # requests.delete(url, **kwargs) # requests.session() ''' ''' reqiests 發起get請求的響應頁面的方法 response = requests.get(url, params, **kwargs) response.request response.content # 獲取的是二進位制文字 response.text # 獲取的是string字串 response.headers # 獲取請求頭 response.encoding # 獲取伺服器的響應頁面的編碼格式 response.url # 獲取瀏覽器向伺服器傳送的URL response.status_code # 獲取伺服器向瀏覽器返回的狀態嗎 response.cookies # 獲取伺服器響應後的cookies ''' ''' requests 發起post請求的響應頁面的方法 (與get相同) response = requests.post(url, data, json, **kwargs) response.cookies response.status_code response.url response.encoding response.headers response.text response.content response.request ''' # response = requests.get(url='https://www.baidu.com/') # Caused by SSLError(CertificateError 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', 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'} # 新增一個verify = False ,取消證書的驗證 response = requests.get(url='https://www.12306.cn/mormhweb/',verify = False,headers = headers) # 將獲取的響應頁面進行編碼 response.encoding = 'utf-8' # 獲取響應頁面的string文字 content = response.text print(content)