利用Python使用代理IP

博主使用代理IP来自于网上免费提供高匿IP的这个网站


用到的库

from bs4 import BeautifulSoup
import random
import urllib.request

下面是对该网站的简单解析提取HTTP的高匿IP
使用BeautifulSoup进行网页解析

def get_proxy_list():
            target = 'http://www.xicidaili.com/nn/' + str(random.randint(0, 100))
            try:
                opener = urllib.request.build_opener()
                #header可以选自己浏览器的
                #样例:[('User-Agent','Mozilla/5.0 (Windows NT 6.1; Win64; x64) ''AppleWebKit/537.36 (KHTML, like Gecko)Chrome/56.0.2924.87 Safari/537.36')]
                opener.addheaders = self.headers
                urllib.request.install_opener(opener)
                html = urllib.request.urlopen(target).read().decode('utf-8')
                tr = BeautifulSoup(html, 'lxml').find_all('tr')
                p = re.compile('<[^>]+>')
                for tag in tr:
                    td_list = tag.find_all('td')
                    if len(td_list) > 0:
                        if str(td_list[5]) == '<td>HTTP</td>':
                        #将爬到的代理IP存到列表里面
                            self.proxy_list.append(p.sub('', str(td_list[1])) + ':' + p.sub('', str(td_list[2])))
            except Exception as b:
                self.logger.exception(b)

接下来就是代理IP的使用
使用的是urllib这个库,到了python3以后这个库可以进行的操作比之前更多,也可以进行一些复杂连接的模拟了

        def init_urllib():
        #这个函数用来初始化urllib的参数
            length = len(self.proxy_list)
            if length == 0:
                get_proxy_list()
            #随机得到一个IP
            ip = random.choice(self.proxy_list)
            self.proxy_list.remove(ip)
            proxy = {'http': ip}
            proxy_support = urllib.request.ProxyHandler(proxy)
            #加载代理
            opener = urllib.request.build_opener(proxy_support)
            opener.addheaders = self.headers
            #初始化urllib
            urllib.request.install_opener(opener)

        def connect(uri):
            html = ''
            flag = 20
            while flag > 0:
                try:
                    html = urllib.request.urlopen(uri).read().decode('utf-8')
                    break
                except Exception as b:
                #这里可以将异常细化,由于是简单实现就不做具体实现了
                    self.logger.exception(b)
                    #实现更换IP重新请求
                    flag -= 1
                    init_urllib()
            return BeautifulSoup(
                html,
                'lxml')

以上就是python对代理IP使用的简单介绍了。


补上博主的新发现,如果要访问HTTPS的网站的话,代理必须是HTTPS的,不然代理的设置会无效。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值