python代理ip怎么写


本文摘自php中文网,作者coldplay.xixi,侵删。

python写代理ip的方法:首先创建代理ip对象,并定制一个opener对象;然后安装opener对象,以后的urlopen就一直使用这个代理地址。

python写代理ip的方法:

方法1:

先创建代理ip对象

1

proxy_support = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})

定制一个opener对象

1

opener = urllib.request.build_opener(proxy_support)

安装这个opener对象,以后的urlopen就一直使用这个代理地址了

1

urllib.request.install_opener(opener)

发出请求时,就是用到这个代理地址了

1

html = urllib.request.urlopen('xxxxxxxxxx').read()

方法2:

先创建代理ip对象

1

proxy_support = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})

定制一个opener对象

1

opener = urllib.request.build_opener(proxy_support)

这里可以直接使用opener对象发出请求

1

html = opener.open('xxxxxxxxx').read()

示例代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

import urllib.request

#这一段三句话是为了请求时带上浏览器标识,因为有的网站看到是爬虫的标识直接返回403

#请求的网站不涉及到提交数据,所以没有给出data参数

url = 'https://whatismyipaddress.com/'

header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}

req = urllib.request.Request(url,headers=header)

#使用代理和还原不使用代理的方法

#if语句相当于一个开关,不要写成True

use_proxy = urllib.request.ProxyHandler({'https':'117.64.149.137:808'})

null_proxy = urllib.request.ProxyHandler()

if True:

    opener = urllib.request.build_opener(use_proxy)

else:

    opener = urllib.request.build_opener(null_proxy)

#根据上面的开关,安装的opener对象是否带有代理地址

urllib.request.install_opener(opener)

#获取返回结果

#同时可以使用html = opener.open(req).read()获取结果

html = urllib.request.urlopen(req).read()

#这网页返回页面的内容太多,在控制台不好查看,

#并且返回的内容是二进制格式,可以直接写入文件,当个网页查看

with open('E:\\whatismyip.html','wb') as file:

    file.write(html)

    print('OK')

相关免费学习推荐:python教程(视频)

以上就是python代理ip怎么写的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python 合并多个字典或映射教程

Python模块查找的原理与方法介绍

Python如何编写公众号

Python下载好了怎么打开

Python标识符命名规范是什么

Python区分大小写吗

Python扩展内置类型的实现方法分析

Python输出数字要带引号吗

使用Python通过win32 com实现word文档的写入与保存方法

Python 实用函数进阶(更新中)

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...