Python urlopen()参数代码示例解析
作者:Hao_ran 时间:2021-05-22 18:26:14
1.data参数
data是可选的,需要使用bytes()方法将参数转化为字节编码格式的内容。如果传递了这个参数,请求方式就不是GET方式,而是POST方式。
import urllib.parse
import urllib.request
data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf8')#使用bytes()方法将参数word(值是hello),转换为字节流(bytes),#该方法的第一个参数需要str类型,需要用urllib.parse模块里的urlencode()方法将参数字典转化为字符串。response = urllib.request.urlopen('http://httpbin.org/post',data = data)
print(response.read())
2.timeout参数
用于设置超时时间,单位为秒,如果超出了设置的这个时间,还没有得到响应,就会抛出异常。可以通过设置这个超时时间来控制一个页面长时间未响应时,就跳过它的抓取。
import socket
import urllib.request
import urllib.error
try:
response = urllib.request.urlopen('http://httpbin.org/get',timeout=0.1)#设置超时时间为0.1s
except urllib.error.URLError as e:
if isinstance(e.reason,socket.timeout):
print('TIME OUT')#如果超时,输出TIME OUT
3.其他参数
context参数,类型必须是ssl.SSLContext类型。
cafile和capath这两个参数分别指定CA证书和它的路径,在请求HTTPS链接时候有用。
cadefault参数已经弃用了,其默认值为False。
来源:https://www.cnblogs.com/Alone-haoran/p/14043965.html
标签:Python,urlopen,参数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
使用layui 的layedit定义自己的toolbar方法
2023-08-24 16:21:43
安装了Office2003补丁之后,access不能用,打不开了
2011-05-12 12:19:00
phpstudy apache开启ssi使用详解
2023-05-25 08:04:44
python递归函数绘制分形树的方法
2021-04-22 02:16:02
![](https://img.aspxhome.com/file/2023/9/67339_0s.jpg)
详解PyQt5 事件处理机制
2023-04-06 00:09:34
![](https://img.aspxhome.com/file/2023/8/81878_0s.gif)
使用apiDoc实现python接口文档编写
2023-10-23 21:28:40
多按钮共存——don’t make me think
2010-01-11 20:20:00
![](https://img.aspxhome.com/file/UploadPic/20101/11/btn_ryan_021-54s.jpg)
Python编程产生非均匀随机数的几种方法代码分享
2023-02-10 02:00:19
![](https://img.aspxhome.com/file/2023/7/67417_0s.png)
python的Crypto模块实现AES加密实例代码
2022-10-02 17:43:10
![](https://img.aspxhome.com/file/2023/4/75124_0s.png)
Python实现发送带有pdf附件的电子邮件
2022-02-01 14:08:05
![](https://img.aspxhome.com/file/2023/4/76924_0s.png)
Python实现简易的图书管理系统
2021-09-12 06:06:21
![](https://img.aspxhome.com/file/2023/0/107550_0s.jpg)
python 异步async库的使用说明
2022-03-03 20:37:01
Python实现的合并两个有序数组算法示例
2021-07-11 10:44:10
Golang中字符串(string)与字节数组([]byte)一行代码互转实例
2023-09-17 14:37:07
![](https://img.aspxhome.com/file/2023/8/101038_0s.png)
在Python中使用gRPC的方法示例
2021-02-02 16:20:21
![](https://img.aspxhome.com/file/2023/5/86565_0s.jpg)
scrapy处理python爬虫调度详解
2021-09-10 11:30:00
防止表格或或div层被撑开的几种方法
2008-01-01 15:33:00
python关闭占用端口方式
2022-03-26 14:10:53
Python实现爬取知乎神回复简单爬虫代码分享
2023-03-23 19:00:10
![](https://img.aspxhome.com/file/2023/8/81778_0s.jpg)
为什么视觉设计师需要懂HTML
2009-06-25 14:16:00