筆記:Python3 爬蟲css
1、爬蟲
html
requests庫是一個經常使用的用於http請求的模塊,它使用python語言編寫,能夠方便的對網頁進行爬取,是學習python爬蟲的較好的http請求模塊。
首先咱們要繼續requests模塊的安裝。python
在windows系統下只須要在命令行輸入命令 pip install requests
便可安裝。linux
在 linux 系統下,只須要輸入命令 sudo pip install requests
,便可安裝。git
因爲pip命令可能安裝失敗因此有時咱們要經過下載第三方庫文件來進行安裝。github
在github上的地址爲:https://github.com/requests/requests
下載文件到本地以後,解壓到python安裝目錄。
以後打開解壓文件,在此處運行命令行並輸入:python setup.py install
便可。web
以後咱們測試requests模塊是否安裝正確,在交互式環境中輸入 import requests
若是沒有任何報錯,說明requests模塊咱們已經安裝成功了json
方法 | 解釋 |
---|---|
requests.request() | 構造一個請求,支持如下各類方法 |
requests.get() | 獲取html的主要方法 |
requests.head() | 獲取html頭部信息的主要方法 |
requests.post() | 向html網頁提交post請求的方法 |
requests.put() | 向html網頁提交put請求的方法 |
requests.patch() | 向html提交局部修改的請求 |
requests.delete() | 向html提交刪除請求 |
這個方法是咱們平時最經常使用的方法之一,經過這個方法咱們能夠了解到其餘的方法,因此咱們詳細介紹這個方法。
具體參數是:windows
r=requests.get(url,params,**kwargs)
**kwargs有如下的參數,對於requests.get,其第一個參數被提出來了。瀏覽器
json:json格式的數據, json合適在相關的html,http相關的web開發中很是常見, 也是http最常用的數據格式, 他是做爲內容部分能夠向服務器提交。
例如:kv = {」key1’: ‘value1’}
r = requests.request(‘POST’, ‘http://python123.io/ws‘, json=kv)
headers:字典是http的相關語,對應了向某個url訪問時所發起的http的頭i字段, 能夠用這個字段來定義http的訪問的http頭,能夠用來模擬任何咱們想模擬的瀏覽器來對url發起訪問。
例子: hd = {‘user-agent’: ‘Chrome/10’}
r = requests.request(‘POST’, ‘http://python123.io/ws‘, headers=hd)
cookies:字典或CookieJar,指的是從http中解析cookie
auth:元組,用來支持http認證功能
files:字典, 是用來向服務器傳輸文件時使用的字段。
例子:fs = {‘files’: open(‘data.txt’, ‘rb’)}
r = requests.request(‘POST’, ‘http://python123.io/ws‘, files=fs)
timeout: 用於設定超時時間, 單位爲秒,當發起一個get請求時能夠設置一個timeout時間, 若是在timeout時間內請求內容沒有返回, 將產生一個timeout的異常。
proxies:字典, 用來設置訪問代理服務器。
allow_redirects: 開關, 表示是否容許對url進行重定向, 默認爲True。
stream: 開關, 指是否對獲取內容進行當即下載, 默認爲True。
verify:開關, 用於認證SSL證書, 默認爲True。
cert: 用於設置保存本地SSL證書路徑
這句代碼是構造一個服務器請求request,返回一個包含服務器資源的response對象。
其中response對象有如下屬性:
屬性 | 說明 |
---|---|
r.status_code | http請求的返回狀態,若爲200則表示請求成功。 |
r.text | http響應內容的字符串形式,即返回的頁面內容 |
r.encoding | 從http header 中猜想的相應內容編碼方式 |
r.apparent_encoding | 從內容中分析出的響應內容編碼方式(備選編碼方式) |
r.content | http響應內容的二進制形式 |
舉例說明:
>>> import requests >>> r=requests.get("http://www.baidu.com") >>> r.status_code 200 >>> r.encoding 'ISO-8859-1' >>> r.apparent_encoding 'utf-8' >>> r.text '<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8>ipt> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ\x9b´å¤\x9a产å\x93\x81</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a com/ class=cp-feedback>æ\x84\x8fè§\x81å\x8f\x8dé¦\x88</a> 京ICPè¯\x81030173å\x8f· <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n' >>> r.encoding='utf-8' >>> r.text '<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta chref=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css="h讀</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意見反饋</a> 京ICP證030173號 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'
(以上r.text內容過長,自行刪除了部分,看出編碼效果便可)
requests庫的異常
注意requests庫有時會產生異常,好比網絡鏈接錯誤、http錯誤異常、重定向異常、請求url超時異常等等。因此咱們須要判斷r.status_codes
是不是200,在這裏咱們怎麼樣去捕捉異常呢?
這裏咱們能夠利用r.raise_for_status()
語句去捕捉異常,該語句在方法內部判斷r.status_code是否等於200,若是不等於,則拋出異常。
因而在這裏咱們有一個爬取網頁的通用代碼框架:
try: r=requests.get(url,timeout=30)#請求超時時間爲30秒 r.raise_for_status()#若是狀態不是200,則引起異常 r.encoding=r.apparent_encoding #配置編碼 return r.text except: return"產生異常"
看代碼:
>>> r=requests.head("http://httpbin.org/get") >>>r.headers {'Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Mon, 20 Nov 2017 08:08:46 GMT', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'X-Powered-By': 'Flask', 'X-Processed-Time': '0.000658988952637', 'Content-Length': '268', 'Via': '1.1 vegur'} >>>r.text ""
一、向url post一個字典:
>>> payload={"key1":"value1","key2":"value2"} >>> r=requests.post("http://httpbin.org/post",data=payload) >>> print(r.text) { "args": {}, "data": "", "files": {}, "form": { "key1": "value1", "key2": "value2" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Content-Length": "23", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "python-requests/2.18.4" }, "json": null, "origin": "218.197.153.150", "url": "http://httpbin.org/post" }
二、向url post 一個字符串,自動編碼爲data
>>>r=requests.post("http://httpbin.org/post",data='helloworld') >>>print(r.text) { "args": {}, "data": "helloworld", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Content-Length": "10", "Host": "httpbin.org", "User-Agent": "python-requests/2.18.4" }, "json": null, "origin": "218.197.153.150", "url": "http://httpbin.org/post" }
看代碼:
>>> payload={"key1":"value1","key2":"value2"} >>> r=requests.put("http://httpbin.org/put",data=payload) >>> print(r.text) { "args": {}, "data": "", "files": {}, "form": { "key1": "value1", "key2": "value2" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Content-Length": "23", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "python-requests/2.18.4" }, "json": null, "origin": "218.197.153.150", "url": "http://httpbin.org/put"
requests.patch和request.put相似。
二者不一樣的是:
當咱們用patch時僅須要提交須要修改的字段。
而用put時,必須將20個字段一塊兒提交到url,未提交字段將會被刪除。
patch的好處是:節省網絡帶寬。
requests.request()支持其餘全部的方法。 requests.request(method,url,**kwargs)
不須要對頭部作任何修改,便可爬網頁
import requests url='http://item.jd.com/2967929.html' try: r=requests.get(url,timeout=30) r.raise_for_status() r.encoding=r.apparent_encoding print(r.text[:1000]) #部分信息 except: print("失敗")
該網頁中對爬蟲進行的爬取作了限制,所以咱們須要假裝本身爲瀏覽器發出的請求。
import requests url='http://www.amazon.cn/gp/product/B01M8L5Z3Y' try: kv={'user_agent':'Mozilla/5.0'} r=requests.get(url,headers=kv)#改變本身的請求數據 r.raise_for_status() r.encoding=r.apparent_encoding print(r.text[1000:2000]) #部分信息 except: print("失敗")
百度的關鍵字接口:
https://www.baidu.com/s?wd=keyword
import requests keyword='python' try: kv={'wd':keyword} r=requests.get('https://www.baidu.com/s',params=kv) r.raise_for_status() r.encoding=r.apparent_encoding print(len(r.text)) except: print("失敗")
import requests import os try: url="http://baishi.baidu.com/watch/02167966440907275567.html"#圖片地址 root="E:/pic/" path=root+url.split("/")[-1] if not os.path.exists(root): #目錄不存在建立目錄 os.mkdir(root) if not os.path.exists(path): #文件不存在則下載 r=requests.get(url) f=open(path,"wb") f.write(r.content) f.close() print("文件下載成功") else: print("文件已經存在") except: print("獲取失敗")
上課代碼;
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/6/12 21:03 # @Author : yangyuanqiang # @File : demon1.py import requests # get請求 # wd = "python" # url = "http://www.baidu.com/s?wd={0}".format(wd) # r = requests.get(url) # r.encoding = "utf-8" # html = r.text # print(html) wd = "python" params = {"wd": "hello"} url = "http://www.baidu.com/s" r = requests.get(url=url, params=params) r.encoding = "utf-8" print(r.url) html = r.text # print(html)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/6/12 21:50 # @Author : yangyuanqiang # @File : demon2.py import requests # post請求 url = "https://www.qiushibaike.com" header = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36"} r = requests.get(url=url, headers=header) print(r.request) print(r.headers) print(r.encoding) print(r.cookies) print(r.cookies.get("_xsrf")) print(r.url) print(r.status_code)