zoukankan      html  css  js  c++  java
  • 爬虫-设置代理ip

    1.为什么要设置代理ip

    在学习Python爬虫的时候,经常会遇见所要爬取的网站采取了反爬取技术导致爬取失败。高强度、高效率地爬取网页信息常常会给网站服务器带来巨大压力,所以同一个IP反复爬取同一个网页,就很可能被封,所以通过设置代理IP来避免被封,从而顺利爬取。

    2.从那里获取免费的IP

    西刺免费代理

    快代理免费代理

    from bs4 import BeautifulSoup
    import requests
    import random
    
    def get_ip_list(url, headers):
        web_data = requests.get(url, headers=headers)
        soup = BeautifulSoup(web_data.text, 'lxml')
        ips = soup.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)
        return ip_list
    
    def get_random_ip(ip_list):
        proxy_list = []
        for ip in ip_list:
            proxy_list.append('http://' + ip)
        proxy_ip = random.choice(proxy_list)
        proxies = {'http': proxy_ip}
        return proxies
    
    if __name__ == '__main__':
        url = 'http://www.xicidaili.com/nn/'
        headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.60 Safari/537.17'
        }
        ip_list = get_ip_list(url, headers=headers)
        proxies = get_random_ip(ip_list)
        print(proxies)

    通过这段代码可以爬取免费代理网站中的代理IP,可以把它封装起来,在使用的时候调用类,也可以把爬取的代理IP存储起来,在使用的时候取出来。

    3.使用代理IP

    # example
    proxies = {
        'https':'https://180.118.135.37:9000'
    }
    res = requests.get(url, headers=headers, proxies=proxies)
  • 相关阅读:
    webpack打包(2)
    webpack打包(1)
    angular(5自定义模块和ionic创建)
    angular(4)路由及其使用
    anjular(3 生命函数及请求)
    Angular(2)
    自学Angular(1)
    Typescript知识总结
    PLC数据采集与MES系统对接
    python格式化日期时间自动补0
  • 原文地址:https://www.cnblogs.com/loveprogramme/p/9451912.html
Copyright © 2011-2022 走看看