Python 爬虫设置动态代理

爬虫的时候,我们用同一个ip反复爬一个网站有可能会被封,这时候就需要使用到代理ip
网上有免费的开放代理,但有些代理ip稳定性差要经常更换且有些爬取后就不可用了还要再筛查
除了免费的外可以向代理供应商购买带代理,它们提供有效代理,并有用户名和密码,和免费的相比多了一个认证
http://www.xicidaili.com/,这个网站列出了很多免费代理。我们以免费的代理为例,如何设置有用户名和密码的代理请查阅其它相关资料

接下来直接上完整代码

# -*-coding:utf-8 -*-
import requests
import random
from bs4 import BeautifulSoup

class IP:
    def __init__(self,headers):
        self.headers=headers

    def get_ip_list(self):
    #获取ip列表
        print("正在获取代理列表...")
        url = 'http://www.xicidaili.com/nn/'
        html = requests.get(url=url, headers=self.headers).text
        soup = BeautifulSoup(html, 'lxml')
        #BeautifulSoup最好这样写soup=BeautifulSoup(html,"lxml")
        ips = soup.find(id='ip_list').find_all('tr')
        ip_list = []
        for i in range(1, len(ips)):
            ip_info = ips[i]
            tds = ip_info.find_all('td')
            ip_list.append(tds[1].text + ':' + tds[2].text)
        print("代理列表抓取成功.")
        return ip_list
        #返回ip地址和端口号组成的列表


    def get_random_ip(self, ip_list):
    #设置随机ip
        print("正在设置随机代理...")
        proxy_list = []
        for ip in ip_list:
            proxy_list.append('http://' + ip)
            #把ip添加到proxy_list中
        proxy_ip = random.choice(proxy_list)
        #随机选取出一个ip
        proxies = {'http': proxy_ip}
        print("代理设置成功.")
        return proxies

    def start(self):
    #开始函数
        ip=self.get_ip_list()
        print self.get_random_ip(ip)

headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/52.0.2743.116 Safari/537.36'}
#我们找到一个写好的headers
ip=IP(headers)
#ip是IP类的一个对象实例
#初始化ip这个实例
ip.start()

我们运行程序,代理设置成功。
这里写图片描述
最后返回了一个list,是一个ip地址和端口号组成的列表
这里写图片描述

之后再根据具体情况来写爬虫






内容参考自:https://blog.csdn.net/JosephPai/article/details/78896613

猜你喜欢

转载自blog.csdn.net/weixin_40208575/article/details/81784025
今日推荐