电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

python urllib庫(kù)的使用詳解

瀏覽:13日期:2022-06-22 15:36:34

相關(guān):urllib是python內(nèi)置的http請(qǐng)求庫(kù),本文介紹urllib三個(gè)模塊:請(qǐng)求模塊urllib.request、異常處理模塊urllib.error、url解析模塊urllib.parse。

1、請(qǐng)求模塊:urllib.request

python2

import urllib2response = urllib2.urlopen(’http://httpbin.org/robots.txt’)

python3

import urllib.requestres = urllib.request.urlopen(’http://httpbin.org/robots.txt’)urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)urlopen()方法中的url參數(shù)可以是字符串,也可以是一個(gè)Request對(duì)象

#url可以是字符串import urllib.requestresp = urllib.request.urlopen(’http://www.baidu.com’)print(resp.read().decode(’utf-8’)) # read()獲取響應(yīng)體的內(nèi)容,內(nèi)容是bytes字節(jié)流,需要轉(zhuǎn)換成字符串

##url可以也是Request對(duì)象import urllib.requestrequest = urllib.request.Request(’http://httpbin.org’)response = urllib.request.urlopen(request)print(response.read().decode(’utf-8’))data參數(shù):post請(qǐng)求

# coding:utf8import urllib.request, urllib.parsedata = bytes(urllib.parse.urlencode({’word’: ’hello’}), encoding=’utf8’)resp = urllib.request.urlopen(’http://httpbin.org/post’, data=data)print(resp.read())urlopen()中的參數(shù)timeout:設(shè)置請(qǐng)求超時(shí)時(shí)間:

# coding:utf8#設(shè)置請(qǐng)求超時(shí)時(shí)間import urllib.requestresp = urllib.request.urlopen(’http://httpbin.org/get’, timeout=0.1)print(resp.read().decode(’utf-8’))響應(yīng)類型:

# coding:utf8#響應(yīng)類型import urllib.requestresp = urllib.request.urlopen(’http://httpbin.org/get’)print(type(resp))

python urllib庫(kù)的使用詳解

響應(yīng)的狀態(tài)碼、響應(yīng)頭:

# coding:utf8#響應(yīng)的狀態(tài)碼、響應(yīng)頭import urllib.requestresp = urllib.request.urlopen(’http://www.baidu.com’)print(resp.status)print(resp.getheaders()) # 數(shù)組(元組列表)print(resp.getheader(’Server’)) # 'Server'大小寫不區(qū)分

200[(’Bdpagetype’, ’1’), (’Bdqid’, ’0xa6d873bb003836ce’), (’Cache-Control’, ’private’), (’Content-Type’, ’text/html’), (’Cxy_all’, ’baidu+b8704ff7c06fb8466a83df26d7f0ad23’), (’Date’, ’Sun, 21 Apr 2019 15:18:24 GMT’), (’Expires’, ’Sun, 21 Apr 2019 15:18:03 GMT’), (’P3p’, ’CP=' OTI DSP COR IVA OUR IND COM '’), (’Server’, ’BWS/1.1’), (’Set-Cookie’, ’BAIDUID=8C61C3A67C1281B5952199E456EEC61E:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com’), (’Set-Cookie’, ’BIDUPSID=8C61C3A67C1281B5952199E456EEC61E; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com’), (’Set-Cookie’, ’PSTM=1555859904; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com’), (’Set-Cookie’, ’delPer=0; path=/; domain=.baidu.com’), (’Set-Cookie’, ’BDSVRTM=0; path=/’), (’Set-Cookie’, ’BD_HOME=0; path=/’), (’Set-Cookie’, ’H_PS_PSSID=1452_28777_21078_28775_28722_28557_28838_28584_28604; path=/; domain=.baidu.com’), (’Vary’, ’Accept-Encoding’), (’X-Ua-Compatible’, ’IE=Edge,chrome=1’), (’Connection’, ’close’), (’Transfer-Encoding’, ’chunked’)]BWS/1.1

使用代理:urllib.request.ProxyHandler():

# coding:utf8proxy_handler = urllib.request.ProxyHandler({’http’: ’http://www.example.com:3128/’})proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()proxy_auth_handler.add_password(’realm’, ’host’, ’username’, ’password’)opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)# This time, rather than install the OpenerDirector, we use it directly:resp = opener.open(’http://www.example.com/login.html’)print(resp.read())2、異常處理模塊:urllib.error異常處理實(shí)例1:

# coding:utf8from urllib import error, requesttry: resp = request.urlopen(’http://www.blueflags.cn’)except error.URLError as e: print(e.reason)

python urllib庫(kù)的使用詳解

異常處理實(shí)例2:

# coding:utf8from urllib import error, requesttry: resp = request.urlopen(’http://www.baidu.com’)except error.HTTPError as e: print(e.reason, e.code, e.headers, sep=’n’)except error.URLError as e: print(e.reason)else: print(’request successfully’)

python urllib庫(kù)的使用詳解

異常處理實(shí)例3:

# coding:utf8import socket, urllib.request, urllib.errortry: resp = urllib.request.urlopen(’http://www.baidu.com’, timeout=0.01)except urllib.error.URLError as e: print(type(e.reason)) if isinstance(e.reason,socket.timeout):print(’time out’)

python urllib庫(kù)的使用詳解

3、url解析模塊:urllib.parseparse.urlencode

# coding:utf8from urllib import request, parseurl = ’http://httpbin.org/post’headers = { ’Host’: ’httpbin.org’, ’User-Agent’: ’Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36’}dict = {’name’: ’Germey’}data = bytes(parse.urlencode(dict), encoding=’utf8’)req = request.Request(url=url, data=data, headers=headers, method=’POST’)resp = request.urlopen(req)print(resp.read().decode(’utf-8’))

{'args': {},'data': '','files': {},'form': {'name': 'Thanlon'},'headers': {'Accept-Encoding': 'identity','Content-Length': '12','Content-Type': 'application/x-www-form-urlencoded','Host': 'httpbin.org','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36'},'json': null,'origin': '117.136.78.194, 117.136.78.194','url': 'https://httpbin.org/post'}add_header方法添加請(qǐng)求頭:

# coding:utf8from urllib import request, parseurl = ’http://httpbin.org/post’dict = {’name’: ’Thanlon’}data = bytes(parse.urlencode(dict), encoding=’utf8’)req = request.Request(url=url, data=data, method=’POST’)req.add_header(’User-Agent’, ’Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36’)resp = request.urlopen(req)print(resp.read().decode(’utf-8’))parse.urlparse:

# coding:utf8from urllib.parse import urlparseresult = urlparse(’http://www.baidu.com/index.html;user?id=1#comment’)print(type(result))print(result)

<class ’urllib.parse.ParseResult’>ParseResult(scheme=’http’, netloc=’www.baidu.com’, path=’/index.html’, params=’user’, query=’id=1’, fragment=’comment’)

from urllib.parse import urlparseresult = urlparse(’www.baidu.com/index.html;user?id=1#comment’, scheme=’https’)print(type(result))print(result)

<class ’urllib.parse.ParseResult’>ParseResult(scheme=’https’, netloc=’’, path=’www.baidu.com/index.html’, params=’user’, query=’id=1’, fragment=’comment’)

# coding:utf8from urllib.parse import urlparseresult = urlparse(’http://www.baidu.com/index.html;user?id=1#comment’, scheme=’https’)print(result)

ParseResult(scheme=’http’, netloc=’www.baidu.com’, path=’/index.html’, params=’user’, query=’id=1’, fragment=’comment’)

# coding:utf8from urllib.parse import urlparseresult = urlparse(’http://www.baidu.com/index.html;user?id=1#comment’,allow_fragments=False)print(result)

ParseResult(scheme=’http’, netloc=’www.baidu.com’, path=’/index.html’, params=’user’, query=’id=1’, fragment=’comment’)

parse.urlunparse:

# coding:utf8from urllib.parse import urlunparsedata = [’http’, ’www.baidu.com’, ’index.html’, ’user’, ’name=Thanlon’, ’comment’]print(urlunparse(data))

python urllib庫(kù)的使用詳解

parse.urljoin:

# coding:utf8from urllib.parse import urljoinprint(urljoin(’http://www.bai.com’, ’index.html’))print(urljoin(’http://www.baicu.com’, ’https://www.thanlon.cn/index.html’))#以后面為基準(zhǔn)

python urllib庫(kù)的使用詳解

urlencode將字典對(duì)象轉(zhuǎn)換成get請(qǐng)求的參數(shù):

# coding:utf8from urllib.parse import urlencodeparams = { ’name’: ’Thanlon’, ’age’: 22}baseUrl = ’http://www.thanlon.cn?’url = baseUrl + urlencode(params)print(url)

python urllib庫(kù)的使用詳解

4、Cookiecookie的獲取(保持登錄會(huì)話信息):

# coding:utf8#cookie的獲取(保持登錄會(huì)話信息)import urllib.request, http.cookiejarcookie = http.cookiejar.CookieJar()handler = urllib.request.HTTPCookieProcessor(cookie)opener = urllib.request.build_opener(handler)res = opener.open(’http://www.baidu.com’)for item in cookie: print(item.name + ’=’ + item.value)

python urllib庫(kù)的使用詳解

MozillaCookieJar(filename)形式保存cookie

# coding:utf8#將cookie保存為cookie.txtimport http.cookiejar, urllib.requestfilename = ’cookie.txt’cookie = http.cookiejar.MozillaCookieJar(filename)handler = urllib.request.HTTPCookieProcessor(cookie)opener = urllib.request.build_opener(handler)res = opener.open(’http://www.baidu.com’)cookie.save(ignore_discard=True, ignore_expires=True)LWPCookieJar(filename)形式保存cookie:

# coding:utf8import http.cookiejar, urllib.requestfilename = ’cookie.txt’cookie = http.cookiejar.LWPCookieJar(filename)handler = urllib.request.HTTPCookieProcessor(cookie)opener = urllib.request.build_opener(handler)res = opener.open(’http://www.baidu.com’)cookie.save(ignore_discard=True, ignore_expires=True)讀取cookie請(qǐng)求,獲取登陸后的信息

# coding:utf8import http.cookiejar, urllib.requestcookie = http.cookiejar.LWPCookieJar()cookie.load(’cookie.txt’, ignore_discard=True, ignore_expires=True)handler = urllib.request.HTTPCookieProcessor(cookie)opener = urllib.request.build_opener(handler)resp = opener.open(’http://www.baidu.com’)print(resp.read().decode(’utf-8’))

以上就是python urllib庫(kù)的使用詳解的詳細(xì)內(nèi)容,更多關(guān)于python urllib庫(kù)的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 医疗仪器模块 健康一体机 多参数监护仪 智慧医疗仪器方案定制 血氧监护 心电监护 -朗锐慧康 | 金联宇电缆总代理-金联宇集团-广东金联宇电缆实业有限公司 | 智慧水务|智慧供排水利信息化|水厂软硬件系统-上海敢创 | 干洗店加盟_洗衣店加盟_干洗店设备-伊蔻干洗「武汉总部」 | 接地电阻测试仪[厂家直销]_电缆故障测试仪[精准定位]_耐压测试仪-武汉南电至诚电力设备 | 护栏打桩机-打桩机厂家-恒新重工 | 东莞喷砂机-喷砂机-喷砂机配件-喷砂器材-喷砂加工-东莞市协帆喷砂机械设备有限公司 | 定硫仪,量热仪,工业分析仪,马弗炉,煤炭化验设备厂家,煤质化验仪器,焦炭化验设备鹤壁大德煤质工业分析仪,氟氯测定仪 | 蚂蚁分类信息系统 - PHP同城分类信息系统 - MayiCMS | OpenI 启智 新一代人工智能开源开放平台 | 万烁建筑设计院-建筑设计公司加盟,设计院加盟分公司,市政设计加盟 | 智慧消防-消防物联网系统云平台 智能化的检漏仪_气密性测试仪_流量测试仪_流阻阻力测试仪_呼吸管快速检漏仪_连接器防水测试仪_车载镜头测试仪_奥图自动化科技 | 植筋胶-粘钢胶-碳纤维布-碳纤维板-环氧砂浆-加固材料生产厂家-上海巧力建筑科技有限公司 | 春腾云财 - 为企业提供专业财税咨询、代理记账服务 | 熔体泵|换网器|熔体齿轮泵|熔体计量泵厂家-郑州巴特熔体泵有限公司 | 铝板冲孔网,不锈钢冲孔网,圆孔冲孔网板,鳄鱼嘴-鱼眼防滑板,盾构走道板-江拓数控冲孔网厂-河北江拓丝网有限公司 | 快速门厂家-快速卷帘门-工业快速门-硬质快速门-西朗门业 | 岸电电源-60HZ变频电源-大功率变频电源-济南诚雅电子科技有限公司 | 早报网| 科研ELISA试剂盒,酶联免疫检测试剂盒,昆虫_植物ELISA酶免试剂盒-上海仁捷生物科技有限公司 | 碳纤维复合材料制品生产定制工厂订制厂家-凯夫拉凯芙拉碳纤维手机壳套-碳纤维雪茄盒外壳套-深圳市润大世纪新材料科技有限公司 | 便携式XPDM露点仪-在线式防爆露点仪-增强型烟气分析仪-约克仪器 冰雕-冰雪世界-大型冰雕展制作公司-赛北冰雕官网 | 派克防爆伺服电机品牌|国产防爆伺服电机|高低温伺服电机|杭州摩森机电科技有限公司 | 干式变压器厂_干式变压器厂家_scb11/scb13/scb10/scb14/scb18干式变压器生产厂家-山东科锐变压器有限公司 | 小型铜米机-干式铜米机-杂线全自动铜米机-河南鑫世昌机械制造有限公司 | 短信营销平台_短信群发平台_106短信发送平台-河南路尚 | 抓斗式清污机|螺杆式|卷扬式启闭机|底轴驱动钢坝|污水处理闸门-方源水利机械 | 减速机电机一体机_带电机减速器一套_德国BOSERL电动机与减速箱生产厂家 | 钛合金标准件-钛合金螺丝-钛管件-钛合金棒-钛合金板-钛合金锻件-宝鸡远航钛业有限公司 | China plate rolling machine manufacturer,cone rolling machine-Saint Fighter | 手术室净化厂家-成都做医院净化工程的公司-四川华锐-15年特殊科室建设经验 | 企业VI设计_LOGO设计公司_品牌商标设计_【北京美研】 | 破碎机锤头_合金耐磨锤头_郑州宇耐机械工程技术有限公司 | 快速门厂家-快速卷帘门-工业快速门-硬质快速门-西朗门业 | 焊接减速机箱体,减速机箱体加工-淄博博山泽坤机械厂 | 浙江富广阀门有限公司| 三板富 | 专注于新三板的第一垂直服务平台 | 二手Sciex液质联用仪-岛津气质联用仪-二手安捷伦气质联用仪-上海隐智科学仪器有限公司 | 全自动实验室洗瓶机,移液管|培养皿|进样瓶清洗机,清洗剂-广州摩特伟希尔机械设备有限责任公司 | 焦作网 WWW.JZRB.COM| 郑州宣传片拍摄-TVC广告片拍摄-微电影短视频制作-河南优柿文化传媒有限公司 |