Python爬虫设置代理IP爬取知乎图片

本文接着前面两文中提到的内容来继续完善我们的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"  #用来测试IP是否可用的url
        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]  #第一个最好设置为自己的本地IP,速度会快一些
        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。

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值