原文链接: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,具体的网页爬取过程和代码介绍可以参看这里:点击打开链接
- import requests
- from bs4 import BeautifulSoup
- import re
- import os.path
-
- user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5)'
- headers = {'User-Agent': user_agent}
-
- def getListProxies():
- session = requests.session()
- page = session.get("http://www.xicidaili.com/nn", headers=headers)
- soup = BeautifulSoup(page.text, 'lxml')
-
- proxyList = []
- taglist = soup.find_all('tr', attrs={'class': re.compile("(odd)|()")})
- for trtag in taglist:
- tdlist = trtag.find_all('td')
- proxy = {'http': tdlist[1].string + ':' + tdlist[2].string,
- 'https': tdlist[1].string + ':' + tdlist[2].string}
- url = "http://ip.chinaz.com/getip.aspx"
- try:
- response = session.get(url, proxies=proxy, timeout=5)
- proxyList.append(proxy)
- if(len(proxyList) == 10):
- break
- except Exception, e:
- continue
-
- return proxyList
然后是通过代理来爬取知乎图片,只需修改上文代码中的 DownloadImgAndWriteToFile 类即可,代码如下:
- import proxyip
-
- class DownloadImgAndWriteToFile(Thread):
- def run(self):
- proxies = proxyip.getListProxies()
- proxy = proxies[0]
- print proxy
- nameNumber = 0
- ipIndex = 1
- global queue
- while isRun:
- image = queue.get()
- queue.task_done()
- suffixNum = image.rfind('.')
- suffix = image[suffixNum:]
- fileName = filePath + os.sep + str(nameNumber) + suffix
- nameNumber += 1
- try:
-
- session.mount(image, HTTPAdapter(max_retries=3))
- response = session.get(image, proxies=proxy, timeout=20)
- contents = response.content
- with open(fileName, "wb") as pic:
- pic.write(contents)
-
- except requests.exceptions.ConnectionError:
- print '连接超时,URL: ', image
- if ipIndex < 10 :
- proxy = proxies[ipIndex]
- print '新IP:Port', proxy
- ipIndex += 1
- except IOError:
- print 'Io error'
- print '图片下载完毕'
注意:这里获取到的IP的下载速度贼慢,本文主要是简单讲解一下requests代理的使用,所以自己用的时候还请换些个快点的IP。