zoukankan      html  css  js  c++  java
  • 爬虫Proxy(代理)的设置

    爬虫的时候默认会使用环境变量 http_proxy 来设置 HTTP Proxy。假如一个网站它会检测某一段时间某个IP 的访问次数,如果访问次数过多,它会禁止你的访问。所以你可以设置一些代理服务器来帮助你做工作,每隔一段时间换一个代理,这样就不怕爬取大量数据的时候突然被封啦。
    本文IP来自国内高匿免费HTTP代理IP__第1页国内高匿 http://www.xicidaili.com/nn/
    这一篇就主要讲讲怎么设置Proxy,上代码!

    from bs4 import BeautifulSoup
    import requests
    import random
    
    def get_ip_list(url, headers):#得到该页面的所有IP
        web_data = requests.get(url, headers=headers)#得到网页响应web_data
        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')
            httptype=str.lower(tds[5].text)#把类型换成小写
            ip_list.append(httptype+'://'+tds[1].text + ':' + tds[2].text)
        return ip_list
    #从众多的IP中随机选一个出来使用
    def get_random_ip(ip_list):
        proxy_ip = random.choice(ip_list)
        return proxy_ip
    
    if __name__ == '__main__':
        url = 'http://www.xicidaili.com/nn/'
        #给请求指定一个请求头来模拟浏览器
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
        ip_list = get_ip_list(url, headers=headers)#调用get_ip_list函数得到IP列表
        proxies = get_random_ip(ip_list)#调用函数get_random_ip从IP列表中随机取用
        print(proxies)
    

      然后!把你得到的IP加进请求,就可以啦

    proxies = {'http': 'http://114.97.184.251:808',
                'https': 'https://119.135.85.253:808' }
    user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
    headers = {'User-Agent': user_agent}
    htmlText = requests.get(url, headers=headers, timeout=3, proxies=proxies).text
    

      

  • 相关阅读:
    各进制转换
    免root xshell连接termux
    sqlmap怎么拿shell
    SSRF漏洞
    国外安全网站、社区论坛、博客、公司、在线工具等整合收集
    渗透测试常用工具问题总结
    cdn绕过
    xss注入
    永恒之蓝(msf17010)kali复现
    文件上传漏洞和绕过
  • 原文地址:https://www.cnblogs.com/navysummer/p/12156803.html
Copyright © 2011-2022 走看看