python3 urllib

1.基本方法

urllib.request.urlopen(urldata=None[timeout]*cafile=Nonecapath=Nonecadefault=Falsecontext=None)

-         url:  須要打開的網址python

-         data:Post提交的數據json

-         timeout:設置網站的訪問超時時間瀏覽器

直接用urllib.request模塊的urlopen()獲取頁面,page的數據格式爲bytes類型,須要decode()解碼,轉換成str類型。服務器

from urllib import request
response = request.urlopen(r'http://www.baidu.com/') 
page = response.read()
page = page.decode('utf-8')
print(page)

urlopen返回對象所提供方法:網站

-         read() , readline() ,readlines() , fileno() , close() :對HTTPResponse類型數據進行操做編碼

-         info():返回HTTPMessage對象,表示遠程服務器返回的頭信息url

-         getcode():返回Http狀態碼。若是是http請求,200請求成功完成;404網址未找到spa

-         geturl():返回請求的url操作系統

 

2.使用Request

urllib.request.Request(url, data=None, headers={}, method=None)

使用request()來包裝請求,再經過urlopen()獲取頁面。code

from urllib import request

url = r'http://www.lagou.com/zhaopin/Python/?labelWords=label'
headers = {
    'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
    'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
    'Connection': 'keep-alive'
}
req = request.Request(url, headers=headers)
page = request.urlopen(req).read()
page = page.decode('utf-8')
print(page)

通過urlencode()轉換後的data數據爲?first=true?pn=1?kd=Python,最後提交的url爲

http://www.lagou.com/jobs/positionAjax.json?first=true?pn=1?kd=Python

Post的數據必須是bytes或者iterable of bytes,不能是str,所以須要進行encode()編碼

用來包裝頭部的數據:

-         User-Agent :這個頭部能夠攜帶以下幾條信息:瀏覽器名和版本號、操做系統名和版本號、默認語言

-         Referer:能夠用來防止盜鏈,有一些網站圖片顯示來源http://***.com,就是檢查Referer來鑑定的

-         Connection:表示鏈接狀態,記錄Session的狀態。

3.Post數據

urllib.request.urlopen(urldata=None[timeout]*cafile=Nonecapath=Nonecadefault=Falsecontext=None)

urlopen()的data參數默認爲None,當data參數不爲空的時候,urlopen()提交方式爲Post。

from urllib import request, parse

url = r'http://www.lagou.com/jobs/positionAjax.json?'
headers = {
    'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
    'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
    'Connection': 'keep-alive'
}
data = {
    'first': 'true',
    'pn': 1,
    'kd': 'Python'
}
data = parse.urlencode(data).encode('utf-8')
req = request.Request(url, headers=headers, data=data)
page = request.urlopen(req).read()
page = page.decode('utf-8')
print(page)

urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None)

urlencode()主要做用就是將url附上要提交的數據。 

通過urlencode()轉換後的data數據爲?first=true?pn=1?kd=Python,最後提交的url爲

http://www.lagou.com/jobs/positionAjax.json?first=true?pn=1?kd=Python

Post的數據必須是bytes或者iterable of bytes,不能是str,所以須要進行encode()編碼

 

 

注:此篇文章寫的更詳細些:

https://yq.aliyun.com/ziliao/109346 

相關文章
相關標籤/搜索