python 爬虫获取有效的IP代理

python 爬虫获取有效的IP代理

通常在爬虫时,网站对于经常访问的IP会有所限制,因此我们需要一个IP代理来帮助我们来爬取网页,那么这些IP代理去哪里找呢?
西刺这个网站提供了很多免费的IP代理,但是这里面并不是都是有效的IP代理,因此还需要筛选,
(感觉西刺的不好用啊)

# @Time :2019/11/9 13:17
# @Auther :Ming
# @Software: PyCharm
import requests
from lxml import etree
def get_proxy():
    proxy = []
    for i in range(1,5):
        url = 'https://www.xicidaili.com/nn/'+ str(i)
        headers ={
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'
        }
        reponse = requests.get(url= url,headers = headers)
        html = reponse.text
        html = etree.HTML(html)
        ip = html.xpath('//tr/td[2]/text()')
        post = html.xpath('//tr/td[3]/text()')
        for a in range(len(ip)):
            proxy.append(ip[a]+':'+post[a])
        return proxy

def check(proxy):
    url = 'http://www.baidu.com'
    for proxy in proxy:
        proxies = {
            'http':'http://'+proxy,
            'https': 'http://'+proxy,
        }
        try:
            response = requests.get(url=url,proxies=proxies)
            if response.status_code == 200:
                with open('2.txt','a',encoding='utf-8') as f:
                    f.write(proxy+'\n')
        except requests.exceptions.ConnectionError as e:
            print('error',e.args)
# from selenium import webdriver
a = get_proxy()
check(a)

爬了一会就两个

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python爬虫代理IP代理是一种在使用Python爬虫时,通过使用代理IP来隐藏真实的IP地址,以防止被目标网站封禁或限制访问。这样可以有效地绕过网站的反爬取技术,并且可以实现高强度、高效率地爬取网页信息而不给网站服务器带来过大的压力。 为了实现代理IP代理,可以按照以下步骤进行操作: 1. 首先,需要获取稳定的代理IP列表。可以参考相关博客或网站,如《python爬虫设置代理ip池——方法(二)》,从中购买或获取代理IP。 2. 接下来,在Python代码中调用代理IP。可以使用以下代码获取代理IP列表并随机选择一个IP作为代理: ```python if __name__ == '__main__': url = 'http://www.xicidaili.com/nn/' ip_list = get_ip_list(url) proxies = get_random_ip(ip_list) print(proxies) ``` 其中,`get_ip_list()`函数用于获取代理IP列表,`get_random_ip()`函数用于从列表中随机选择一个IP作为代理。 通过以上步骤,就可以使用代理IP实现Python爬虫的代理IP代理功能了。这样可以有效地绕过网站的反爬取技术,并且提高爬取效率。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [python爬虫设置代理ip池——方法(一)](https://blog.csdn.net/weixin_40372371/article/details/80154707)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值