温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python代理ip的方法

发布时间:2020-09-02 10:07:01 来源:亿速云 阅读:120 作者:小新 栏目:编程语言

python代理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的方法大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI