Python學習筆記__12.9章 urlib

來源:互聯網
上載者:User

標籤:程式設計語言   Python   

# 這是學習廖雪峰老師python教程的學習筆記

1、概覽

urllib提供了一系列用於操作URL的功能。

urllib中包括了四個模組,包括

  • urllib.request:可以用來發送request和擷取request的結果

  • urllib.error:包含了urllib.request產生的異常

  • urllib.parse:用來解析和處理URL

  • urllib.robotparse:用來解析頁面的robots.txt檔案

1.1、urllib.request

urllib的request模組可以非常方便地抓取URL內容。

它會先發送一個GET請求到指定的頁面,然後返回HTTP的響應:

1)對豆瓣的一個URL進行抓取,並返迴響應

from urllib import request

 

# request模組調用urlopen方法開啟網址

with request.urlopen('https://api.douban.com/v2/book/2129650') as f:

    data = f.read() #返回的網頁內容

    print('Status:', f.status, f.reason)

    for k, v in f.getheaders():

        print('%s: %s' % (k, v))

    print('Data:', data.decode('utf-8'))

2)類比iPhone 6去請求豆瓣首頁

類比瀏覽器發送GET請求,使用Request對象。通過往Request對象添加HTTP頭,我們就可以把請求偽裝成各種瀏覽器

from urllib import request

 

req = request.Request('http://www.douban.com/') #建立了一個Request對象 req是類

# 添加請求的頭資訊

req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')

with request.urlopen(req) as f: #將Request對象作為url傳入

    print('Status:', f.status, f.reason)

    for k, v in f.getheaders():

        print('%s: %s' % (k, v))

    print('Data:', f.read().decode('utf-8'))

1.2、Post

如果要以POST發送一個請求,只需要把參數data以bytes形式傳入。

1)我們類比一個微博登入,先讀取登入的郵箱和口令,然後按照weibo.cn的登入頁的格式以username=xxx&password=xxx的編碼傳入

from urllib import request, parse

 

print('Login to weibo.cn...')

email = input('Email: ')

passwd = input('Password: ')

login_data = parse.urlencode([  # 用parse的urlencode方法,對要傳過去的資料進行編碼

    ('username', email),

    ('password', passwd),

    ('entry', 'mweibo'),

    ('client_id', ''),

    ('savestate', '1'),

    ('ec', ''),

    ('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F')

])

 

req = request.Request('https://passport.weibo.cn/sso/login')   # 建立Request 對象

req.add_header('Origin', 'https://passport.weibo.cn')

req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')

req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')

 

with request.urlopen(req, data=login_data.encode('utf-8')) as f: #data用來指明發往伺服器請求中的額外的資訊

    print('Status:', f.status, f.reason)

    for k, v in f.getheaders():

        print('%s: %s' % (k, v))

    print('Data:', f.read().decode('utf-8'))

1.3、Header

1)如果還需要更複雜的控制,比如通過一個Proxy去訪問網站,我們需要利用ProxyHandler來處理

proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'}) #建立代理

proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()  #設定基礎認證管理,用代理處理身份認證

# relam:代理的範圍,'host':代理url,

# 用一個使用編程提供的代理url(’host‘)替換預設的ProxyHandler

proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler) # 返回一個 OpenerDirector 執行個體

with opener.open('http://www.example.com/login.html') as f:  # 訪問網址

    pass

1.4、小結

urllib提供的功能就是利用程式去執行各種HTTP請求。如果要類比瀏覽器完成特定功能,需要把請求偽裝成瀏覽器。偽裝的方法是先監控瀏覽器發出的請求,再根據瀏覽器的要求標頭來偽裝,User-Agent頭就是用來標識瀏覽器的。

1.5、擴充文檔

python3網路爬蟲一《使用urllib.request發送請求》 (76067790)

Python中urlopen()介紹 (https://www.cnblogs.com/zyq-blog/p/5606760.html)

python 爬蟲之為什麼使用opener對象以及為什麼要建立全域預設的opener對象 (https://www.cnblogs.com/cunyusup/p/7341829.html)

2、例子

1、利用urllib讀取JSON,然後將JSON解析為Python對象:

# -*- coding: utf-8 -*-

from urllib import request

import json

 

def fetch_data(url):

    with request.urlopen(url) as f:

        data = json.loads(f.read().decode('utf-8')) #將讀到的網頁內容解碼,再由json.loads()還原序列化為Python對象

        return data

 

 

 

# 測試

URL = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json'

data = fetch_data(URL)

print(data)

assert data['query']['results']['channel']['location']['city'] == 'Beijing'

print('ok')


Python學習筆記__12.9章 urlib

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.