python设置代理ip爬取知乎图片

原文链接:http://blog.csdn.net/willib/article/details/52374507


本文接着前面两文中提到的内容来继续完善我们的Python爬虫。上文地址:通过Python爬虫爬取知乎某个问题下的图片

设置代理的方式很简单,可以看看这里Requests的官方文档,这里也有对应的中文版介绍,点击打开链接

先简单说下requests代理的使用,摘自上述提到的文档:

如果需要使用代理,你可以通过为任意请求方法提供 proxies 参数来配置单个请求:

import requests

proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",
}

requests.get("http://example.org", proxies=proxies)

你也可以通过环境变量 HTTP_PROXY 和 HTTPS_PROXY 来配置代理。

$ export HTTP_PROXY="http://10.10.1.10:3128"
$ export HTTPS_PROXY="http://10.10.1.10:1080"

$ python
>>> import requests
>>> requests.get("http://example.org")

若你的代理需要使用HTTP Basic Auth,可以使用 http://user:password@host/ 语法:

proxies = {
    "http": "http://user:pass@10.10.1.10:3128/",
}

要为某个特定的连接方式或者主机设置代理,使用 scheme://hostname 作为 key, 它会针对指定的主机和连接方式进行匹配。

proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}

注意,代理 URL 必须包含连接方式。

下面看一个例子,接着上文提到的高匿代理,我们获取该网站第一页上可用的IP和端口,下面的代码段把它放在了一个单独的模块中,命名为: 'proxyip',接着我们调用该模块可以直接获取到可用的10个代理ip,具体的网页爬取过程和代码介绍可以参看这里:点击打开链接

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import requests  
  2. from bs4 import BeautifulSoup  
  3. import re  
  4. import os.path  
  5.   
  6. user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5)'  
  7. headers = {'User-Agent': user_agent}  
  8.   
  9. def getListProxies():  
  10.     session = requests.session()  
  11.     page = session.get("http://www.xicidaili.com/nn", headers=headers)  
  12.     soup = BeautifulSoup(page.text, 'lxml')  
  13.   
  14.     proxyList = []  
  15.     taglist = soup.find_all('tr', attrs={'class': re.compile("(odd)|()")})  
  16.     for trtag in taglist:  
  17.         tdlist = trtag.find_all('td')  
  18.         proxy = {'http': tdlist[1].string + ':' + tdlist[2].string,  
  19.                  'https': tdlist[1].string + ':' + tdlist[2].string}  
  20.         url = "http://ip.chinaz.com/getip.aspx"  #用来测试IP是否可用的url  
  21.         try:  
  22.             response = session.get(url, proxies=proxy, timeout=5)  
  23.             proxyList.append(proxy)  
  24.             if(len(proxyList) == 10):  
  25.                 break  
  26.         except Exception, e:  
  27.             continue  
  28.   
  29.     return proxyList  

然后是通过代理来爬取知乎图片,只需修改上文代码中的 DownloadImgAndWriteToFile 类即可,代码如下:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import proxyip  
  2.   
  3. class DownloadImgAndWriteToFile(Thread):  
  4.     def run(self):  
  5.         proxies = proxyip.getListProxies()  
  6.         proxy = proxies[0]  #第一个最好设置为自己的本地IP,速度会快一些  
  7.         print proxy  
  8.         nameNumber = 0  
  9.         ipIndex = 1  
  10.         global queue  
  11.         while isRun:  
  12.             image = queue.get()  
  13.             queue.task_done()  
  14.             suffixNum = image.rfind('.')  
  15.             suffix = image[suffixNum:]  
  16.             fileName = filePath + os.sep + str(nameNumber) + suffix  
  17.             nameNumber += 1  
  18.             try:  
  19.                 # 设置超时重试次数及超时时间单位秒  
  20.                 session.mount(image, HTTPAdapter(max_retries=3))  
  21.                 response = session.get(image, proxies=proxy, timeout=20)  
  22.                 contents = response.content  
  23.                 with open(fileName, "wb") as pic:  
  24.                     pic.write(contents)  
  25.   
  26.             except requests.exceptions.ConnectionError:  
  27.                 print '连接超时,URL: ', image  
  28.                 if ipIndex < 10 :  
  29.                     proxy = proxies[ipIndex]  
  30.                     print '新IP:Port', proxy  
  31.                     ipIndex += 1  
  32.             except IOError:  
  33.                 print 'Io error'  
  34.         print '图片下载完毕'  

注意:这里获取到的IP的下载速度贼慢,本文主要是简单讲解一下requests代理的使用,所以自己用的时候还请换些个快点的IP。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值