Python3學(xué)習(xí)urllib的使用方法示例
urllib是python的一個(gè)獲取url(Uniform Resource Locators,統(tǒng)一資源定址符)了,可以利用它來(lái)抓取遠(yuǎn)程的數(shù)據(jù)進(jìn)行保存,本文整理了一些關(guān)于urllib使用中的一些關(guān)于header,代理,超時(shí),認(rèn)證,異常處理處理方法。
1.基本方法
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
- url: 需要打開(kāi)的網(wǎng)址
- data:Post提交的數(shù)據(jù)
- timeout:設(shè)置網(wǎng)站的訪(fǎng)問(wèn)超時(shí)時(shí)間
直接用urllib.request模塊的urlopen()獲取頁(yè)面,page的數(shù)據(jù)格式為bytes類(lèi)型,需要decode()解碼,轉(zhuǎn)換成str類(lèi)型。
from urllib import request
response = request.urlopen(r'http://python.org/') # <http.client.HTTPResponse object at 0x00000000048BC908> HTTPResponse類(lèi)型
page = response.read()
page = page.decode('utf-8')
urlopen返回對(duì)象提供方法:
- read() , readline() ,readlines() , fileno() , close() :對(duì)HTTPResponse類(lèi)型數(shù)據(jù)進(jìn)行操作
- info():返回HTTPMessage對(duì)象,表示遠(yuǎn)程服務(wù)器返回的頭信息
- getcode():返回Http狀態(tài)碼。如果是http請(qǐng)求,200請(qǐng)求成功完成;404網(wǎng)址未找到
- geturl():返回請(qǐng)求的url
1、簡(jiǎn)單讀取網(wǎng)頁(yè)信息
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()來(lái)包裝請(qǐng)求,再通過(guò)urlopen()獲取頁(yè)面。
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)壓縮,無(wú)需解壓")
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信息可以通過(guò)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 = "登錄賬號(hào)"
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錯(cuò)誤
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://www.dbjr.com.cn /"
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://www.dbjr.com.cn /"
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、超時(shí)
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://www.dbjr.com.cn /')
a = urllib.request.urlopen(req).read()
print(a)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Django migrate報(bào)錯(cuò)的解決方案
在講解如何解決migrate報(bào)錯(cuò)原因前,我們先要了解migrate做了什么事情,本文就詳細(xì)的介紹migrate使用以及出現(xiàn)問(wèn)題的解決,感興趣的可以了解一下2021-05-05
Python多線(xiàn)程編程(二):?jiǎn)?dòng)線(xiàn)程的兩種方法
這篇文章主要介紹了Python多線(xiàn)程編程(一):?jiǎn)?dòng)線(xiàn)程的兩種方法,本文講解了將函數(shù)傳遞進(jìn)Thread對(duì)象、繼承自threading.Thread類(lèi)兩種方法,需要的朋友可以參考下2015-04-04
python 隨機(jī)密碼生成器的實(shí)現(xiàn)示例
隨機(jī)密碼生成器是一種非常有用的工具,它可以幫助我們生成隨機(jī)的、復(fù)雜的密碼,提高我們的賬戶(hù)安全性,本文就來(lái)介紹一下python 隨機(jī)密碼生成器的實(shí)現(xiàn)示例,感興趣的可以了解一下2023-11-11
Python辦公自動(dòng)化之將任意文件轉(zhuǎn)為PDF格式
這種把某個(gè)文件轉(zhuǎn)為pdf枯燥無(wú)聊的工作,既沒(méi)有什么技術(shù)含量又累. 今天辰哥就教大家將任意文件批量轉(zhuǎn)為PDF,這里以日常辦公的word、excel、ppt為例,這三種格式的文件轉(zhuǎn)為PDF.需要的朋友可以參考下2021-06-06
python進(jìn)度條庫(kù)tqdm的基本操作方法
這篇文章主要介紹了python進(jìn)度條庫(kù)tqdm的基本操作方法,tqdm實(shí)時(shí)輸出處理進(jìn)度而且占用的CPU資源非常少,支持windows、Linux、mac等系統(tǒng),支持循環(huán)處理、多進(jìn)程、遞歸處理、還可以結(jié)合linux的命令來(lái)查看處理情況等優(yōu)點(diǎn),下面對(duì)其更多內(nèi)容詳細(xì)介紹,需要的朋友可以參考一下2022-03-03
Python簡(jiǎn)單的制作圖片驗(yàn)證碼實(shí)例
本篇文章主要介紹了Python簡(jiǎn)單的制作圖片驗(yàn)證碼實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
在linux下實(shí)現(xiàn) python 監(jiān)控usb設(shè)備信號(hào)
今天小編就為大家分享一篇在linux下實(shí)現(xiàn) python 監(jiān)控usb設(shè)備信號(hào),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07

