爬蟲請求模塊

1 版本

 python2 : urllib  urllib2

python3 : 把urllib 和 urllib2合併,urllib.request

 

2 常用方法

2.1urllib.request.urlopen("網址")    向網站發起一個請求並獲取響應

     2.1.1字節流  = response.read()

     字符串 = response.read().decode("utf-8")31

     encode() : 字符串--->bytes

     decode(): bytes-->字符串

2.2  重構User-Agent

   2.2.1  不支持重構User-Agent  :urlopen()

  2.2.2 支持重構   User-Agent  :urllib.request.Request("網址",headers="字典")

     User-Agent 是爬蟲和反爬蟲鬥爭的第一步,發送請求必須帶User-Agent 

     2.2.2.1 使用流程

       2.2.2.1.1 利用Request方法構建請求對象

       2.2.2.1.2  利用urlopen()獲取響應對象

      2.2.2.1.3    利用響應對象的read().decode("utf-8") 獲取內容

  2.2.2.2 響應對象 response的方法

     2.2.2.2.1  read()  讀取服務器響應的內容

     2.2.2.2.2 getcode()

         作用  返回HTTP響應碼   print(response.getcode())

              200  成功

              4xx  服務器頁面出錯        5xx   服務器出錯

     2.2.2.2.3 geturl()

          作用   返回實際數據的url (防止重定向問題)

3 urllib.parse 模塊

   3.1 urlencode(字典)

        urlencode({"wd":"美女"})       wd=%e%rr.......

  3.2 quote(字符串)

    

aseurl = "http://www.baidu.com/s?wd="
key = input("請輸入要搜索的內容:")
#用quote()編碼

key = urllib.parse.quote(key)

url = baseurl + key
print(url)

 

發請求 - 響應(html源碼)- 解析

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章