Python3:urllib模塊的使用

Python3:urllib模塊的使用
1.基本方法
html

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
    url:  須要打開的網址
    data:Post提交的數據
    timeout:設置網站的訪問超時時間

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

from urllib import request
response = request.urlopen(r'http://python.org/')
page = response.read()
page = page.decode('utf-8')
urlopen返回對象提供方法:

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

info():返回HTTPMessage對象,表示遠程服務器返回的頭信息
getcode():返回Http狀態碼。若是是http請求,200請求成功完成;404網址未找到
geturl():返回請求的url

 2.使用Requestjson

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

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

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')

 用來包裝頭部的數據:服務器

User-Agent :這個頭部能夠攜帶以下幾條信息:瀏覽器名和版本號、操做系統名和版本號、默認語言
Referer:能夠用來防止盜鏈,有一些網站圖片顯示來源http://***.com,就是檢查Referer來鑑定的
Connection:表示鏈接狀態,記錄Session的狀態。
ide

3.Post數據網站

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=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')

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

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

data = {
     'first': 'true',
     'pn': 1,
     'kd': 'Python'
}
data = parse.urlencode(data).encode('utf-8')
通過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()編碼
固然,也能夠把data的數據封裝在urlopen()參數中:
page = request.urlopen(req, data=data).read()

   在這裏就要說點實際應用的事兒了:

從json中取出的數據類型和數據以下:
<class 'dict'> {'install': {'install_date': '2018/09/26', 'install_result': 'success'}}
通過轉碼:company_data = parse.urlencode(data).encode('utf-8')
變成這樣:b'install=%7B%27install_date%27%3A+%272018%2F09%2F26%27%2C+%27install_result%27%3A+%27success%27%7D'
服務器端接收數據:
data = request.POST.get("company_data")
數據類型、數據分別以下:
<class 'str'> {"install": {"install_result": "success", "install_date": "2018/09/26"}}

 我想要的字典變成了字符串,這就得找解決辦法(用json去解決問題):

客戶端:
import json
with open('1.json', 'r') as f:
    data = json.load(f)

data = {"company_data": json.dumps(data)}

# urlopen()的data參數默認爲None,當data參數不爲空的時候,urlopen()提交方式爲Post
from urllib import request, parse
url = r'http://192.168.165.4:8000/show/report/'
company_data = parse.urlencode(data).encode('utf-8')
req = request.Request(url, data=company_data)
print(company_data)
page = request.urlopen(req).read()
page = page.decode('utf-8')
服務器端:
@csrf_exempt
def receive_data(request):
    data = request.POST.get("company_data")
    if data:
        try:
            data = json.loads(data)
            print("企業數據", type(data), data)
            return HttpResponse(data)
        except ValueError as e:
            print(str(e))
    else:
        return HttpResponse("no data")

 4.處理異常

 1 from urllib import request, parse
 2 def get_page(url):
 3     headers = {
 4           'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ''
 5                         r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
 6         'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
 7         'Connection': 'keep-alive'
 8         }
 9     data = {
10          'first': 'true',
11          'pn': 1,
12          'kd': 'Python'
13      }
14     data = parse.urlencode(data).encode('utf-8')
15     req = request.Request(url, headers=headers)
16     try:
17         page = request.urlopen(req, data=data).read()
18         page = page.decode('utf-8')
19     except request.HTTPError as e:
20         print(e.code())
21         print(e.read().decode('utf-8'))
22     return page
get_page

5.使用代理

urllib.request.ProxyHandler(proxies=None)
當須要抓取的網站設置了訪問限制,這時就須要用到代理來抓取數據。

data = {
     'first': 'true',
     'pn': 1,
     'kd': 'Python'
}
proxy = request.ProxyHandler({'http': '5.22.195.215:80'})  # 設置proxy
opener = request.build_opener(proxy)  # 掛載opener
request.install_opener(opener)  # 安裝opener
data = parse.urlencode(data).encode('utf-8')
page = opener.open(url, data).read()
page = page.decode('utf-8')

 

python3-urllib參考:https://www.cnblogs.com/Lands-ljk/p/5447127.html

相關文章
相關標籤/搜索