最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python3學(xué)習(xí)urllib的使用方法示例

 更新時間:2017年11月29日 10:45:46   作者:Data&Truth  
本篇文章主要介紹了Python3學(xué)習(xí)urllib的使用方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

urllib是python的一個獲取url(Uniform Resource Locators,統(tǒng)一資源定址符)了,可以利用它來抓取遠(yuǎn)程的數(shù)據(jù)進(jìn)行保存,本文整理了一些關(guān)于urllib使用中的一些關(guān)于header,代理,超時,認(rèn)證,異常處理處理方法。

1.基本方法

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

  1. url:  需要打開的網(wǎng)址
  2. data:Post提交的數(shù)據(jù)
  3. timeout:設(shè)置網(wǎng)站的訪問超時時間

直接用urllib.request模塊的urlopen()獲取頁面,page的數(shù)據(jù)格式為bytes類型,需要decode()解碼,轉(zhuǎn)換成str類型。

from urllib import request
response = request.urlopen(r'http://python.org/') # <http.client.HTTPResponse object at 0x00000000048BC908> HTTPResponse類型
page = response.read()
page = page.decode('utf-8')

urlopen返回對象提供方法:

  1. read() , readline() ,readlines() , fileno() , close() :對HTTPResponse類型數(shù)據(jù)進(jìn)行操作
  2. info():返回HTTPMessage對象,表示遠(yuǎn)程服務(wù)器返回的頭信息
  3. getcode():返回Http狀態(tài)碼。如果是http請求,200請求成功完成;404網(wǎng)址未找到
  4. geturl():返回請求的url

1、簡單讀取網(wǎng)頁信息

import urllib.request 
response = urllib.request.urlopen('http://python.org/') 
html = response.read() 

2、使用request

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

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

import urllib.request 
req = urllib.request.Request('http://python.org/') 
response = urllib.request.urlopen(req) 
the_page = response.read() 

3、發(fā)送數(shù)據(jù),以登錄知乎為例

''''' 
Created on 2016年5月31日 
 
@author: gionee 
''' 
import gzip 
import re 
import urllib.request 
import urllib.parse 
import http.cookiejar 
 
def ungzip(data): 
  try: 
    print("嘗試解壓縮...") 
    data = gzip.decompress(data) 
    print("解壓完畢") 
  except: 
    print("未經(jīng)壓縮,無需解壓") 
   
  return data 
     
def getXSRF(data): 
  cer = re.compile('name=\"_xsrf\" value=\"(.*)\"',flags = 0) 
  strlist = cer.findall(data) 
  return strlist[0] 
 
def getOpener(head): 
  # cookies 處理 
  cj = http.cookiejar.CookieJar() 
  pro = urllib.request.HTTPCookieProcessor(cj) 
  opener = urllib.request.build_opener(pro) 
  header = [] 
  for key,value in head.items(): 
    elem = (key,value) 
    header.append(elem) 
  opener.addheaders = header 
  return opener 
# header信息可以通過firebug獲得 
header = { 
  'Connection': 'Keep-Alive', 
  'Accept': 'text/html, application/xhtml+xml, */*', 
  'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3', 
  'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0', 
  'Accept-Encoding': 'gzip, deflate', 
  'Host': 'www.zhihu.com', 
  'DNT': '1' 
} 
 
url = 'http://www.zhihu.com/' 
opener = getOpener(header) 
op = opener.open(url) 
data = op.read() 
data = ungzip(data) 
_xsrf = getXSRF(data.decode()) 
 
url += "login/email" 
email = "登錄賬號" 
password = "登錄密碼" 
postDict = { 
  '_xsrf': _xsrf, 
  'email': email, 
  'password': password, 
  'rememberme': 'y'  
} 
postData = urllib.parse.urlencode(postDict).encode() 
op = opener.open(url,postData) 
data = op.read() 
data = ungzip(data) 
 
print(data.decode()) 

4、http錯誤

import urllib.request 
req = urllib.request.Request('http://www.lz881228.blog.163.com ') 
try: 
  urllib.request.urlopen(req) 
except urllib.error.HTTPError as e: 
print(e.code) 
print(e.read().decode("utf8")) 

5、異常處理

from urllib.request import Request, urlopen 
from urllib.error import URLError, HTTPError 
 
req = Request("http://www.abc.com /") 
try: 
  response = urlopen(req) 
except HTTPError as e: 
  print('The server couldn't fulfill the request.') 
  print('Error code: ', e.code) 
except URLError as e: 
  print('We failed to reach a server.') 
  print('Reason: ', e.reason) 
else: 
  print("good!") 
  print(response.read().decode("utf8")) 

6、http認(rèn)證

import urllib.request 
 
# create a password manager 
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() 
 
# Add the username and password. 
# If we knew the realm, we could use it instead of None. 
top_level_url = "http://m.fzitv.net /" 
password_mgr.add_password(None, top_level_url, 'rekfan', 'xxxxxx') 
 
handler = urllib.request.HTTPBasicAuthHandler(password_mgr) 
 
# create "opener" (OpenerDirector instance) 
opener = urllib.request.build_opener(handler) 
 
# use the opener to fetch a URL 
a_url = "http://m.fzitv.net /" 
x = opener.open(a_url) 
print(x.read()) 
 
# Install the opener. 
# Now all calls to urllib.request.urlopen use our opener. 
urllib.request.install_opener(opener) 
a = urllib.request.urlopen(a_url).read().decode('utf8') 
 
print(a) 

7、使用代理

import urllib.request 
 
proxy_support = urllib.request.ProxyHandler({'sock5': 'localhost:1080'}) 
opener = urllib.request.build_opener(proxy_support) 
urllib.request.install_opener(opener) 
 
a = urllib.request.urlopen("http://www.baidu.com ").read().decode("utf8") 
print(a) 

8、超時

import socket 
import urllib.request 
 
# timeout in seconds 
timeout = 2 
socket.setdefaulttimeout(timeout) 
 
# this call to urllib.request.urlopen now uses the default timeout 
# we have set in the socket module 
req = urllib.request.Request('http://m.fzitv.net /') 
a = urllib.request.urlopen(req).read() 
print(a) 

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Pytorch 如何訓(xùn)練網(wǎng)絡(luò)時調(diào)整學(xué)習(xí)率

    Pytorch 如何訓(xùn)練網(wǎng)絡(luò)時調(diào)整學(xué)習(xí)率

    這篇文章主要介紹了Pytorch 如何訓(xùn)練網(wǎng)絡(luò)時調(diào)整學(xué)習(xí)率的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • pandas刪除指定行詳解

    pandas刪除指定行詳解

    這篇文章主要介紹了pandas刪除指定行的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • 詳解Django中六個常用的自定義裝飾器

    詳解Django中六個常用的自定義裝飾器

    這篇文章主要介紹了詳解Django中六個常用的自定義裝飾器,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07
  • Python中的內(nèi)存管理之python list內(nèi)存使用詳解

    Python中的內(nèi)存管理之python list內(nèi)存使用詳解

    這篇文章主要介紹了Python中的內(nèi)存管理之python list內(nèi)存使用詳解,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-09-09
  • Python第三方模塊apscheduler安裝和基本使用

    Python第三方模塊apscheduler安裝和基本使用

    本文主要介紹了Python第三方模塊apscheduler安裝和基本使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • python 基礎(chǔ)學(xué)習(xí)第二彈 類屬性和實例屬性

    python 基礎(chǔ)學(xué)習(xí)第二彈 類屬性和實例屬性

    本人c程序員,最近開始學(xué)python,深深的被python的強(qiáng)大所吸引,今后也會把學(xué)到的點點滴滴記錄下來,現(xiàn)在分享一下關(guān)于類屬性和實例屬性的一些問題,很基礎(chǔ)的東西
    2012-08-08
  • python中對%、~含義的解釋

    python中對%、~含義的解釋

    這篇文章主要介紹了python中對%、~含義的解釋,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • python實現(xiàn)百度語音識別api

    python實現(xiàn)百度語音識別api

    這篇文章主要為大家詳細(xì)介紹了python實現(xiàn)百度語音識別api,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • Python的子線程和子進(jìn)程是如何手動結(jié)束的?

    Python的子線程和子進(jìn)程是如何手動結(jié)束的?

    今天給大家?guī)淼氖顷P(guān)于Python的相關(guān)知識,文章圍繞著如何手動結(jié)束Python的子線程和子進(jìn)程展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • 使用pygame模塊編寫貪吃蛇的實例講解

    使用pygame模塊編寫貪吃蛇的實例講解

    下面小編就為大家分享一篇使用pygame模塊編寫貪吃蛇的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-02-02

最新評論

城口县| 定边县| 桃江县| 龙州县| 武乡县| 札达县| 三门峡市| 易门县| 大安市| 海口市| 仁化县| 永靖县| 长乐市| 保康县| 江陵县| 渝北区| 易门县| 汕尾市| 绥阳县| 淅川县| 炎陵县| 革吉县| 五常市| 平山县| 台东市| 株洲市| 渭源县| 安徽省| 玉树县| 舒城县| 靖边县| 南京市| 西林县| 北辰区| 阳谷县| 乌兰县| 五峰| 中山市| 库车县| 黔西县| 金塔县|