编写Python代码以获取免费的HTTPS代理
要获取免费的HTTPS代理,可以使用`requests_proxies`库。首先安装该库: ```bash pip install requests-proxies ``` 然后使用以下Python代码获取免费的HTTPS代理: ```python import requests from requests_proxies import RandomProxy def get_free_https_proxy(): proxies = RandomProxy() return proxies.get('https') if __name__ == '__main__': proxy = get_free_https_proxy() print(f'免费HTTPS代理: {proxy}') ``` 这段代码会从`requests_proxies`库中随机获取一个免费的HTTPS代理,并将其打印出来。
前言
大家用Python爬网页时候,爬快了被封IP,爬慢了,等的着急,这时候就需要httpsdai理来切换IP了。
分享一段获取免费的httpsdai理Python代码,可以快速获取网络上免费的httpsdai理。
Python代码
frommultiprocessing.dummyimportLockimportreimportrequestsimportrandomimporttimeheaders={"User-Agent":'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/91.0.4472.77Safari/537.36Edg/91.0'}#source可以替换,github上有很多source='https://github.com/roosterkid/openproxylist/blob/main/HTTPS_RAW.txt'defget_proxies(source_url=source):print('Trygetproxiesfrom:',source_url)resp=requests.get(source_url,verify=False,headers=headers)ifresp.status_code!=200:print('Requestforsourcepagefailed!')raiseException('GetproxiesFailed!')resp.encoding='utf8'raws=re.findall(r'(d{1,3}.d{1,3}.d{1,3}.d{1,3}:d{1,6})',resp.text)proxies=[]forrinraws:proxies.append('https://'+r)returnproxiesdefget_proxies_retry(retries=5):ifretries:try:proxies=get_proxies()print('Getproxies:',len(proxies))returnproxiesexceptExceptionase:print('Getproxiesfailed!')print(e)print('Remainretrytimes:',retries)retries-=1time.sleep(3)returnget_proxies_retry(retries)else:raiseException("Cannotgetproxieswithretrying!")#包裹成一个类,方便调用classProxyPool():def__init__(self,minimal=10)->None:self.proxies=[]#多线程爬虫时,加个锁self._lock=Lock()self.minimal=minimaldefpick_proxy(self):#选择proxy时,检查代{过}{滤}理池是否够用self._fill_pool()returnrandom.choice(self.proxies)defremove_proxy(self,proxy):try:self.proxies.remove(proxy)print('Removeproxy:',proxy)except:print('Proxyhasbeenremoved!')def_fill_pool(self):#少于minimal个代{过}{滤}理时,更新代{过}{滤}理池iflen(self.proxies)<self.minimal:#加锁,防止同时重复调用self._lock.acquire()iflen(self.proxies)<self.minimal:self.proxies=get_proxies_retry()self._lock.release()使用复制代码隐藏代码proxyPool=ProxyPool()proxy=proxyPool.pick_proxy()requests.get('url',proxies={'https':proxy})#如果代{过}{滤}理不可用,删除proxyPool.remove_proxy(proxy)
问题:从GitHub获取代{过}{滤}理列表时,偶尔会失败,可能是我的网络问题。