广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python urllib库的使用详解
  • 292
分享到

python urllib库的使用详解

2024-04-02 19:04:59 292人浏览 薄情痞子

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

摘要

目录1、请求模块:urllib.request data参数:post请求urlopen()中的参数timeout:设置请求超时时间:响应类型:响应的状态码、响应头:使用代理:url

相关:urllib是python内置的Http请求库,本文介绍urllib三个模块:请求模块urllib.request、异常处理模块urllib.error、url解析模块urllib.parse。

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.request

resp = urllib.request.urlopen('http://www.baidu.com')
print(resp.read().decode('utf-8'))  # read()获取响应体的内容,内容是bytes字节流,需要转换成字符串

##url可以也是Request对象
import urllib.request

request = urllib.request.Request('http://httpbin.org')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

data参数:post请求


# coding:utf8
import urllib.request, urllib.parse

data = 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.request

resp = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
print(resp.read().decode('utf-8'))

响应类型:


# coding:utf8
#响应类型
import urllib.request

resp = urllib.request.urlopen('http://httpbin.org/get')
print(type(resp))

响应的状态码、响应头:


# coding:utf8
#响应的状态码、响应头
import urllib.request

resp = 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:utf8
proxy_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:utf8
from urllib import error, request

try:
    resp = request.urlopen('http://www.blueflags.cn')
except error.URLError as e:
    print(e.reason)

异常处理实例2:


# coding:utf8
from urllib import error, request

try:
    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')

异常处理实例3:


# coding:utf8
import Socket, urllib.request, urllib.error

try:
    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')

3、url解析模块:urllib.parse

parse.urlencode


# coding:utf8
from urllib import request, parse

url = '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:utf8
from urllib import request, parse

url = '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:utf8
from urllib.parse import urlparse

result = 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 urlparse

result = 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:utf8
from urllib.parse import urlparse

result = 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:utf8
from urllib.parse import urlparse

result = 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:utf8
from urllib.parse import urlunparse

data = ['http', 'www.baidu.com', 'index.html', 'user', 'name=Thanlon', 'comment']
print(urlunparse(data))

parse.urljoin:


# coding:utf8
from urllib.parse import urljoin

print(urljoin('http://www.bai.com', 'index.html'))
print(urljoin('http://www.baicu.com', 'https://www.thanlon.cn/index.html'))#以后面为基准

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


# coding:utf8
from urllib.parse import urlencode

params = {
    'name': 'Thanlon',
    'age': 22
}
baseUrl = 'http://www.thanlon.cn?'
url = baseUrl + urlencode(params)
print(url)

4、Cookie

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


# coding:utf8
#cookie的获取(保持登录会话信息)
import urllib.request, http.cookiejar

cookie = 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)

MozillaCookieJar(filename)形式保存cookie


# coding:utf8
#将cookie保存为cookie.txt
import http.cookiejar, urllib.request

filename = '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:utf8
import http.cookiejar, urllib.request

filename = '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:utf8
import http.cookiejar, urllib.request

cookie = 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库的使用详解的详细内容,更多关于python urllib库的资料请关注编程网其它相关文章!

--结束END--

本文标题: python urllib库的使用详解

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

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

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

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

下载Word文档
猜你喜欢
  • python urllib库的使用详解
    目录1、请求模块:urllib.request data参数:post请求urlopen()中的参数timeout:设置请求超时时间:响应类型:响应的状态码、响应头:使用代理:url...
    99+
    2022-11-12
  • Python urllib库的使用指南详解
    目录urlopenRequestUser-Agent添加更多的Header信息添加一个特定的header随机添加/修改User-Agent所谓网页抓取,就是把URL地址中指定的网络资...
    99+
    2022-11-10
  • Python爬虫库urllib的使用教程详解
    目录Python urllib库urllib.request模块urlopen函数Request 类urllib.error模块URLError 示例HTTPError示例...
    99+
    2022-11-21
    Python爬虫库urllib使用 Python urllib使用 Python urllib
  • Python爬虫之urllib库详解
    目录一、说明:二、urllib四个模块组成:三、urllib.request1、urlopen函数2、response 响应类型3、Request对象 4、高级请求方式四、urlli...
    99+
    2022-11-13
  • urllib库如何在python中使用
    今天就跟大家聊聊有关urllib库如何在python中使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。1、请求模块:urllib.requestpython2import urll...
    99+
    2023-06-14
  • Python爬虫urllib和requests的区别详解
    我们讲了requests的用法以及利用requests简单爬取、保存网页的方法,这节课我们主要讲urllib和requests的区别。 1、获取网页数据 第一步,引入模块。 两者引入...
    99+
    2022-11-12
  • 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 urllib如何使用
    本篇内容介绍了“Python urllib如何使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!一、简介urllib 库,它是 P...
    99+
    2023-07-04
  • 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库中parse模块urlparse的使用方法
    这篇文章主要介绍了python爬虫urllib库中parse模块urlparse的使用方法,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。在python爬虫urllib库中,u...
    99+
    2023-06-14
  • Python jiaba库的使用详解
    目录jiaba库的使用1、jieba库的安装2、统计荷塘月色词频总结jiaba库的使用 jieba库是一款优秀的 Python 第三方中文分词库,jieba 支持三种分词模式:精确模...
    99+
    2022-11-12
  • 【urllib的使用(上)】
    文章目录 一、urllib的基本用法二、urllib类型和方法类型方法 三、urllib下载下载网页下载图片下载视频 四、请求对象的定制五、编解码1.get请求方式urllib.par...
    99+
    2023-09-15
    python 前端 爬虫
  • Python中的pathlib库使用详解
    目录1. pathlib库介绍2. pathlib库下Path类的基本使用2.1 获取文件名2.2 获取文件前缀和后缀2.3 获取文件的文件夹及上一级、上上级文件夹2.4 获取该文件...
    99+
    2022-11-11
  • 详解Python中datetime库的使用
    目录1. datetime 库概述2. 拓展: 1970年1月1日3. datetime 库解析1. datetime 库概述 以不同格式显示日期和时间是程序中最常用到的功能。Pyt...
    99+
    2023-05-18
    Python datetime datetime
  • Python学习:使用urllib模块读
    request 还是requests? 来自Python小白真诚的求助!没办法,只能求助Google了! 原来,Requests模块是一个用于网络访问的模块,网络访问就是利用某些参数发送请求,然后获取我们想要的信息。其实类似的模块...
    99+
    2023-01-31
    模块 Python urllib
  • Python的urllib模块怎么用
    这篇文章主要介绍了Python的urllib模块怎么用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Python的urllib模块怎么用文章都会有所收获,下面我们一起来看看吧。一、Python urllib 模...
    99+
    2023-06-30
  • 关于python爬虫应用urllib库作用分析
    目录一、urllib库是什么?二、urllib库的使用urllib.request模块urllib.parse模块利用try-except,进行超时处理status状态码 &...
    99+
    2022-11-12
  • python中time库使用详解
    目录time库的使用:时间获取:(1)time函数(2)localtime()函数和gmtime()函数(3)ctime()函数(与asctime()函数为一对互补函数) ...
    99+
    2022-11-11
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作