iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >urllib库如何在python中使用
  • 933
分享到

urllib库如何在python中使用

2023-06-14 12:06:07 933人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

今天就跟大家聊聊有关urllib库如何在python中使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。1、请求模块:urllib.requestPython2import urll

今天就跟大家聊聊有关urllib库如何在python中使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

1、请求模块:urllib.request

Python2

import urllib2
response = urllib2.urlopen('Http://httpbin.org/robots.txt')

python3

import urllib.request
res = 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参数可以是字符串,也可以是一个Request对象

#url可以是字符串import urllib.requestresp = urllib.request.urlopen('http://www.baidu.com')print(resp.read().decode('utf-8'))  # read()获取响应体的内容,内容是bytes字节流,需要转换成字符串
##url可以也是Request对象import urllib.requestrequest = urllib.request.Request('http://httpbin.org')response = urllib.request.urlopen(request)print(response.read().decode('utf-8'))

data参数:post请求

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()中的参数timeout:设置请求超时时间:

# coding:utf8#设置请求超时时间import urllib.requestresp = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)print(resp.read().decode('utf-8'))

响应类型:

# coding:utf8#响应类型import urllib.requestresp = urllib.request.urlopen('http://httpbin.org/get')print(type(resp))

urllib库如何在python中使用

响应的状态码、响应头:

# coding:utf8#响应的状态码、响应头import urllib.requestresp = urllib.request.urlopen('http://www.baidu.com')print(resp.status)print(resp.getheaders())  # 数组(元组列表)print(resp.getheader('Server'))  # "Server"大小写不区分

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

异常处理实例1:

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

urllib库如何在python中使用

异常处理实例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')

urllib库如何在python中使用

异常处理实例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')

urllib库如何在python中使用

3、url解析模块:urllib.parse

parse.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方法添加请求头:

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

urllib库如何在python中使用

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'))#以后面为基准

urllib库如何在python中使用

urlencode将字典对象转换成get请求的参数:

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

urllib库如何在python中使用

4、Cookie

cookie的获取(保持登录会话信息):

# coding:utf8#cookie的获取(保持登录会话信息)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)

urllib库如何在python中使用

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请求,获取登陆后的信息

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

看完上述内容,你们对urllib库如何在python中使用有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注编程网Python频道,感谢大家的支持。

--结束END--

本文标题: urllib库如何在python中使用

本文链接: https://www.lsjlt.com/news/270875.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • urllib库如何在python中使用
    今天就跟大家聊聊有关urllib库如何在python中使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。1、请求模块:urllib.requestpython2import urll...
    99+
    2023-06-14
  • Python urllib如何使用
    本篇内容介绍了“Python urllib如何使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!一、简介urllib 库,它是 P...
    99+
    2023-07-04
  • python urllib库的使用详解
    目录1、请求模块:urllib.request data参数:post请求urlopen()中的参数timeout:设置请求超时时间:响应类型:响应的状态码、响应头:使用代理:url...
    99+
    2024-04-02
  • Python爬虫进阶之如何使用urllib库
    这篇文章主要介绍了Python爬虫进阶之如何使用urllib库,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。python的数据类型有哪些python的数据类型:1. 数字类型...
    99+
    2023-06-14
  • Python爬虫中urllib库怎么用
    这篇文章给大家分享的是有关Python爬虫中urllib库怎么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。一、说明:urllib库是python内置的一个http请求库,requests库就是基于该库开发出来...
    99+
    2023-06-29
  • Python urllib库的使用指南详解
    目录urlopenRequestUser-Agent添加更多的Header信息添加一个特定的header随机添加/修改User-Agent所谓网页抓取,就是把URL地址中指定的网络资...
    99+
    2024-04-02
  • Python中urllib库和requests库区别
    本篇内容主要讲解“Python中urllib库和requests库区别”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Python中urllib库和requests库区别”吧!一、前言在使用Pyt...
    99+
    2023-06-15
  • Polars库如何在python中使用
    这期内容当中小编将会给大家带来有关Polars库如何在python中使用,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。python可以做什么Python是一种编程语言,内置了许多有效的工具,Python几...
    99+
    2023-06-14
  • 如何在python中使用jieba库
    这篇文章将为大家详细讲解有关如何在python中使用jieba库,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。python可以做什么Python是一种编程语言,内置了许多有效的工具,Pyth...
    99+
    2023-06-07
  • 如何在python中使用matlab库
    这期内容当中小编将会给大家带来有关如何在python中使用matlab库,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。Python的优点有哪些1、简单易用,与C/C++、Java、C# 等传统语言相比,P...
    99+
    2023-06-14
  • 如何在Python中使用curses库
    本篇文章为大家展示了如何在Python中使用curses库,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。1、Python内置了curses库,但是对于Windows 操作系统需要安装一个补丁以进行适...
    99+
    2023-06-15
  • 如何在python中使用gin库
    这篇文章将为大家详细讲解有关如何在python中使用gin库,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。Python主要用来做什么Python主要应用于:1、Web开发;2、数据科学研究;...
    99+
    2023-06-14
  • 如何在python中使用gensim库
    这篇文章给大家介绍如何在python中使用gensim库,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。python主要应用领域有哪些1、云计算,典型应用OpenStack。2、WEB前端开发,众多大型网站均为Pytho...
    99+
    2023-06-14
  • 如何在python中使用munch库
    这篇文章给大家介绍如何在python中使用munch库,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。1. 安装方法使用如下命令进行安装$ python -m pip instal...
    99+
    2023-06-15
  • python中urllib用法
    非常抱歉,由于您没有提供文章标题,我无法为您生成一篇高质量的文章。请您提供文章标题,我将尽快为您生成一篇优质的文章。...
    99+
    2024-05-15
  • Python爬虫库urllib的使用教程详解
    目录Python urllib库urllib.request模块urlopen函数Request 类urllib.error模块URLError 示例HTTPError示例...
    99+
    2022-11-21
    Python爬虫库urllib使用 Python urllib使用 Python urllib
  • python爬虫urllib库中parse模块urlparse的使用方法
    这篇文章主要介绍了python爬虫urllib库中parse模块urlparse的使用方法,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。在python爬虫urllib库中,u...
    99+
    2023-06-14
  • Python爬虫之Urllib库的基本使
    # get请求 import urllib.request response = urllib.request.urlopen("http://www.baidu.com") print(response.read().decode('...
    99+
    2023-01-30
    爬虫 Python Urllib
  • Python3 Urllib库的基本使用
    一、什么是Urllib   Urllib库是Python自带的一个http请求库,包含以下几个模块: urllib.request    请求模块 urllib.error        异常处理模块 urllib.parse      ...
    99+
    2023-01-31
    Urllib
  • 如何在python中中使用excel模块库
    本篇文章为大家展示了如何在python中中使用excel模块库,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。openpyxlopenpyxl是⼀个Python库,用于读取/写⼊Excel 2010 ...
    99+
    2023-06-15
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作