python--爬虫之通过ip代理实现爬虫

  1. 什么是IP代理
    pass
  2. 怎么通过ip代理来访问
    pass
  3. 获取免费的IP代理,并过滤无效ip
# coding=utf-8
import requests
from bs4 import BeautifulSoup
from random import choice

#传入网址,解析网址,获取对应的ip,并返回对应ip

def get_ip_proxy(url):
    '''
    这里传入对应IP网址,然后通过解析对应网址来将ip和端口组装成字符串装进列表
    通过一个生成器返回一个ip,传入test_ip这个函数进行ip请求测试

    '''
    headers = {

            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36',
            'Host': 'www.xicidaili.com'
        }
    ret = requests.get(url,headers=headers)
    print(ret.status_code)
    soup=BeautifulSoup(ret.content.decode(),'lxml')
    ip_area=soup.find_all('table',{'id':'ip_list'})[0].find_all('td')
    ip_list=[]
    ip_index=1
    port_index=2
    try:
        for index in ip_area:
            ip_list.append(ip_area[ip_index].text+':'+ip_area[port_index].text)
            ip_index+=+8
            port_index+=8
    except IndexError:
        for ip in ip_list:
            yield ip

#对获取ip进行测试,过滤掉无效的ip
def test_ip(ip_adr):
    '''
     通过get_ip_proxy中返回的ip,加入代理池,然后对代理池的ip进行get请求测试,这里只判断状态码,如果ip确实可用就打印出对应的ip
    '''
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'
    }
    proxy={'http':ip_adr}
    status=requests.get('https://www.baidu.com/',headers=headers,proxies=proxy)
    if status.status_code==200:
        print(ip_adr)

def main():
    '''
    这里显示主要函数逻辑
    '''
    url = 'https://www.xicidaili.com/'
    for ip_adress in get_ip_proxy(url):
        test_ip(ip_adress)

if __name__ == '__main__':
    main()

#输出结果:
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值