溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

爬蟲中的Proxy-Tunnel是如何自主切換IP的

發(fā)布時間:2021-10-14 15:18:41 來源:億速云 閱讀:133 作者:iii 欄目:編程語言

這篇文章主要講解了“爬蟲中的Proxy-Tunnel是如何自主切換IP的”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“爬蟲中的Proxy-Tunnel是如何自主切換IP的”吧!

在采集數(shù)據(jù)的過程這歐中我們經(jīng)常會遇到這樣的問題,目標(biāo)網(wǎng)站需要登錄,獲取數(shù)據(jù)的兩個請求在一個IP下完成,這時我們就只需對這組請求設(shè)置相同Proxy-Tunnel。例如:Proxy-Tunnel: 12345, 該組請求在代理有效期內(nèi)使用相同的代理IP。這就是億牛云的Proxy-Tunnel自主切換IP,該模式適合一些需要登陸、Cookie緩存處理等爬蟲需要精確控制IP切換時機(jī)的業(yè)務(wù)。 爬蟲程序可以通過設(shè)置HTTP頭Proxy-Tunnel: 隨機(jī)數(shù), 當(dāng)隨機(jī)數(shù)相同時,訪問目標(biāo)網(wǎng)站的代理IP相同。

#! -*- encoding:utf-8 -*-    import urllib2    import random    import httplib    class HTTPSConnection(httplib.HTTPSConnection):        def set_tunnel(self, host, port=None, headers=None):            httplib.HTTPSConnection.set_tunnel(self, host, port, headers)            if hasattr(self, 'proxy_tunnel'):                self._tunnel_headers['Proxy-Tunnel'] = self.proxy_tunnel    class HTTPSHandler(urllib2.HTTPSHandler):        def https_open(self, req):            return urllib2.HTTPSHandler.do_open(self, HTTPSConnection, req, context=self._context)    # 要訪問的目標(biāo)頁面    targetUrlList = [        "https://httpbin.org/ip",        "https://httpbin.org/headers",        "https://httpbin.org/user-agent",    ]    # 代理服務(wù)器(產(chǎn)品官網(wǎng) www.16yun.cn)    proxyHost = "t.16yun.cn"    proxyPort = "31111"    # 代理驗(yàn)證信息    proxyUser = "username"    proxyPass = "password"    proxyMeta = "http://%(user)s:%(pass)s@%(host)s:%(port)s" % {        "host": proxyHost,        "port": proxyPort,        "user": proxyUser,        "pass": proxyPass,    }    # 設(shè)置 http和https訪問都是用HTTP代理    proxies = {        "http": proxyMeta,        "https": proxyMeta,    }    #  設(shè)置IP切換頭    tunnel = random.randint(1, 10000)    headers = {"Proxy-Tunnel": str(tunnel)}    HTTPSConnection.proxy_tunnel = tunnel    proxy = urllib2.ProxyHandler(proxies)    opener = urllib2.build_opener(proxy, HTTPSHandler)    urllib2.install_opener(opener)    # 訪問三次網(wǎng)站,使用相同的tunnel標(biāo)志,均能夠保持相同的外網(wǎng)IP    for i in range(3):        for url in targetUrlList:            r = urllib2.Request(url)            print(urllib2.urlopen(r).read())

感謝各位的閱讀,以上就是“爬蟲中的Proxy-Tunnel是如何自主切換IP的”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對爬蟲中的Proxy-Tunnel是如何自主切換IP的這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI