Python,小白自學爬蟲

來源:互聯網
上載者:User

標籤:coding   url參數   方式   form   als   cat   檔案   none   輸出   

學習內容來源自:部落格園 金角大王

 

2018.7.22

Urllib庫的基本使用                                                                                                                                   

什麼是Urllib?

 

Urllib是python內建的HTTP請求庫
包括以下基礎模組:
urllib.request       請求模組
urllib.error       異常處理模組
urllib.parse      url解析模組
urllib.robotparser  robots.txt解析模組

 

 urllib.request的使用                                           
  • urlopen

urllib.request.urlopen

完整參數:urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

一般常用:urllib.requeset.urlopen(url,data,timeout)

  • url參數

簡單栗子

 

1 import urllib.request2 3 response = urllib.request.urlopen(‘https://bj.ke.com/‘)4 print(response.read().decode(‘utf-8‘))

 

結果:抓取貝殼網首頁的Javascript中的內容

response.read()可以擷取到網頁的內容,decode(‘utf-8‘)可以是抓取到的內容以utf-8的格式輸出

  • data參數

 

網站:http://httpbin.org 

該網站可以用來類比各中請求

栗子:

 

1 import urllib.parse2 import urllib.request3 4 data = bytes(urllib.parse.urlencode({‘word‘: ‘hello‘}), encoding=‘utf8‘)5 print(data)6 response = urllib.request.urlopen(‘http://httpbin.org/post‘, data=data)7 print(response.read())

 

備忘:

1、urllib.parse  url解析模組

2、通過bytes(urllib.parse.urlencode())可以將post資料進行轉換放到urllib.request.urlopen的data參數中,這樣就完成了一次post請求

3、添加data參數的時候就是以post請求方式請求,如果沒有data參數就是get請求方式

4、GET和POST的區別就是:請求的資料GET是在url中,POST則是存放在頭部

GET:向指定的資源發出“顯示”請求。使用GET方法應該只用在讀取資料,而不應當被用於產生“副作用”的操作中,例如在Web Application中。其中一個原因是GET可能會被網路蜘蛛等隨意訪問

POST:向指定資源提交資料,請求伺服器進行處理(例如提交表單或者上傳檔案)。資料被包含在請求本文中。這個請求可能會建立新的資源或修改現有資源,或二者皆有。

  • timeout參數

{"args":{},"data":"","files":{},"form":{"word":"shang"},"headers":{"Accept-Encoding":"identity","Connection":"close","Content-Length":"10","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"Python-urllib/3.7"},"json":null,"origin":"183.240.196.58","url":"http://httpbin.org/post"}

b‘{"args":{},"headers":{"Accept-Encoding":"identity","Connection":"close","Host":"httpbin.org","User-Agent":"Python-urllib/3.7"},"origin":"183.240.196.58","url":"http://httpbin.org/get"}\n‘

 

Python,小白自學爬蟲

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.