網絡請求(一)

urlencode函數:編碼

urlencode可以把字典數據轉換爲URL編碼的數據。

from urllib import parse

data = {'name':'老王','age':18,'greet':'hello world'}

qs = parse.urlencode(data)
print(qs)

#name=%E8%80%81%E7%8E%8B&age=18&greet=hello+world

parse_qs函數:解碼

可以將經過編碼後的url參數進行解碼

print(parse.parse_qs(qs))
# {'name': ['老王'], 'age': ['18'], 'greet': ['hello world']}

urlparse和urlsplit函數:解析url

from urllib import parse

url = 'http://www.baidu.com/index.html;user?id=S#comment'

result = parse.urlparse(url)
# result = parse.urlsplit(url)

print(result)
print(result.scheme)
print(result.netloc)
print(result.path)
#urlparse裏有params屬性,而urlsplit沒有這個params屬性。
print(result.params)

request.Request類:網絡請求 可以增加請求頭

from urllib import request

headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 			(KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
}

rq = request.Request('https://www.baidu.com/',headers=headers)


resp = request.urlopen(rq)

print(resp.read())

ProxyHandler處理器(代理設置):封ip問題

  1. 代理原理:在請求目的網站之前,先請求代理服務器,然後讓代理服務器去請求目的網站,代理服務器拿到目的網站的數據後,再轉發給我們的代碼。

  2. http://httpbin.org:這個網站可以方便的查看http請求的一些參數。
    在這裏插入圖片描述

  3. 在代碼中使用代理 示例:

    # 使用代理
    # 步驟
    url = 'http://httpbin.org/ip'
    #1. 使用ProxyHandler,傳入代理構建一個handler
    handler = request.ProxyHandler({'http':'122.193.244.243:9999'})
    #2. 使用上面創建的handler構建一個opener
    opener = request.build_opener(handler)
    #3. 使用opener去發送一個請求
    resp = opener.open(url)
    print(resp.read())
    
    #--coding:utf-8--
    
    from urllib import request
    # 沒有使用代理
    # url = 'http://httpbin.org/ip'
    # resp = request.urlopen(url)
    # print(resp.read())
    
    
    # 使用代理
    # 步驟
    url = 'http://httpbin.org/ip'
    #1. 使用ProxyHandler,傳入代理構建一個handler
    handler = request.ProxyHandler({'http':'122.193.244.243:9999'})
    #2. 使用上面創建的handler構建一個opener
    opener = request.build_opener(handler)
    #3. 使用opener去發送一個請求
    resp = opener.open(url)
    print(resp.read())
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章