python 通过代理抓取数据

来源:互联网 发布:苹果手机阅读软件 编辑:程序博客网 时间:2024/05/22 11:51

前言

有一些网站和数据,是不通过代理访问不到的(不管是不是正经的 :) )。如何用Python抓取这些数据呢?

正文

1,设置代理

因为我们的程序是在终端里执行,所以需要先设置一下:
- 设置在终端下能够使用代理
- 启用ss代理,且本地代理为socks5://127.0.0.1:1080

可以参考文章:Make the python requests work via socks proxy on CentOS server

2,安装第三方库

pip install requestspip install lxmlpip install PySocks

3,抓取脚本

import requestsimport sslfrom urllib.request import urlretrieveimport socketimport socksdef get_pic():    # 设置代理    socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 1080)    socket.socket = socks.socksocket    # 想要抓取的图片 重定向后的链接    url = 'your-url'    # 方法1    ssl._create_default_https_context = ssl._create_unverified_context    urlretrieve(url, 'my.jpg')    # 方法2    # session = requests.Session()    # req = session.get(url)    # with open('./my.jpg', 'wb') as f:    #     f.write(req.content)    #     f.flush()if __name__ == '__main__':    get_pic()

4,其它方式

还有一种方式,是使用支持SOCKS协议代理的requests,方法请参考: 
python-requests socks5

参考:
Python中Request 使用socks5代理的两种方法(个人推荐方法二)
python-requests socks5
Make the python requests work via socks proxy on CentOS server
requests 通过 socks5
py脚本走代理

原创粉丝点击