色综合图-色综合图片-色综合图片二区150p-色综合图区-玖玖国产精品视频-玖玖香蕉视频

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

python爬蟲(chóng)構(gòu)建代理ip池抓取數(shù)據(jù)庫(kù)的示例代碼

瀏覽:2日期:2022-07-10 13:18:57

爬蟲(chóng)的小伙伴,肯定經(jīng)常遇到ip被封的情況,而現(xiàn)在網(wǎng)絡(luò)上的代理ip免費(fèi)的已經(jīng)很難找了,那么現(xiàn)在就用python的requests庫(kù)從爬取代理ip,創(chuàng)建一個(gè)ip代理池,以備使用。

本代碼包括ip的爬取,檢測(cè)是否可用,可用保存,通過(guò)函數(shù)get_proxies可以獲得ip,如:{’HTTPS’: ’106.12.7.54:8118’}

下面放上源代碼,并詳細(xì)注釋:

import requestsfrom lxml import etreefrom requests.packages import urllib3import random, time urllib3.disable_warnings() def spider(pages, max_change_porxies_times=300): ''' 抓取 XiciDaili.com 的 http類型-代理ip-和端口號(hào) 將所有抓取的ip存入 raw_ips.csv 待處理, 可用 check_proxies() 檢查爬取到的代理ip是否可用 ----- :param pages:要抓取多少頁(yè) :return:無(wú)返回 ''' s = requests.session() s.trust_env = False s.verify = False urls =com/nn/{}’ proxies = {} try_times = 0 for i in range(pages): url = urls.format(i + 1) s.headers = { ’Accept’: ’text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8’, ’Accept-Encoding’: ’gzip, deflate, br’, ’Accept-Language’: ’zh-CN,zh;q=0.9’, ’Connection’: ’keep-alive’, ’Referer’: urls.format(i if i > 0 else ’’), ’User-Agent’: ’Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36’} while True: content = s.get(url, headers=s.headers, proxies=proxies) time.sleep(random.uniform(1.5, 4)) # 每讀取一次頁(yè)面暫停一會(huì),否則會(huì)被封 if content.status_code == 503: # 如果503則ip被封,就更換ipproxies = get_proxies()try_times += 1print(f’第{str(try_times):0>3s}次變更,當(dāng)前{proxies}’)if try_times > max_change_porxies_times: print(’超過(guò)最大嘗試次數(shù),連接失敗!’) return -1continue else:break # 如果返回碼是200 ,就跳出while循環(huán),對(duì)爬取的頁(yè)面進(jìn)行處理 print(f’正在抓取第{i+1}頁(yè)數(shù)據(jù),共{pages}頁(yè)’) for j in range(2, 102): # 用簡(jiǎn)單的xpath提取http,host和port tree = etree.HTML(content.text) http = tree.xpath(f’//table[@id='ip_list']/tr[{j}]/td[6]/text()’)[0] host = tree.xpath(f’//table[@id='ip_list']/tr[{j}]/td[2]/text()’)[0] port = tree.xpath(f’//table[@id='ip_list']/tr[{j}]/td[3]/text()’)[0] check_proxies(http, host, port) # 檢查提取的代理ip是否可用 def check_proxies(http, host, port, test_url=’http://www.baidu.com’): ''' 檢測(cè)給定的ip信息是否可用 根據(jù)http,host,port組成proxies,對(duì)test_url進(jìn)行連接測(cè)試,如果通過(guò),則保存在 ips_pool.csv 中 :param http: 傳輸協(xié)議類型 :param host: 主機(jī) :param port: 端口號(hào) :param test_url: 測(cè)試ip :return: None ''' proxies = {http: host + ’:’ + port} try: res = requests.get(test_url, proxies=proxies, timeout=2) if res.status_code == 200: print(f’{proxies}檢測(cè)通過(guò)’) with open(’ips_pool.csv’, ’a+’) as f:f.write(’,’.join([http, host, port]) + ’n’) except Exception as e: # 檢測(cè)不通過(guò),就不保存,別讓報(bào)錯(cuò)打斷程序 print(e) def check_local_ip(fn, test_url): ''' 檢查存放在本地ip池的代理ip是否可用 通過(guò)讀取fn內(nèi)容,加載每一條ip對(duì)test_url進(jìn)行連接測(cè)試,鏈接成功則儲(chǔ)存在 ips_pool.csv 文件中 :param fn: filename,儲(chǔ)存代理ip的文件名 :param test_url: 要進(jìn)行測(cè)試的ip :return: None ''' with open(fn, ’r’) as f: datas = f.readlines() ip_pools = [] for data in datas: # time.sleep(1) ip_msg = data.strip().split(’,’) http = ip_msg[0] host = ip_msg[1] port = ip_msg[2] proxies = {http: host + ’:’ + port} try: res = requests.get(test_url, proxies=proxies, timeout=2) if res.status_code == 200:ip_pools.append(data)print(f’{proxies}檢測(cè)通過(guò)’)with open(’ips_pool.csv’, ’a+’) as f: f.write(’,’.join([http, host, port]) + ’n’) except Exception as e: print(e) continue def get_proxies(ip_pool_name=’ips_pool.csv’): ''' 從ip池獲得一個(gè)隨機(jī)的代理ip :param ip_pool_name: str,存放ip池的文件名, :return: 返回一個(gè)proxies字典,形如:{’HTTPS’: ’106.12.7.54:8118’} ''' with open(ip_pool_name, ’r’) as f: datas = f.readlines() ran_num = random.choice(datas) ip = ran_num.strip().split(’,’) proxies = {ip[0]: ip[1] + ’:’ + ip[2]} return proxies if __name__ == ’__main__’: t1 = time.time() spider(pages=3400) t2 = time.time() print(’抓取完畢,時(shí)間:’, t2 - t1) # check_local_ip(’raw_ips.csv’,’http://www.baidu.com’)

以上就是python爬蟲(chóng)構(gòu)建代理ip池抓取數(shù)據(jù)庫(kù)的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于python爬蟲(chóng)構(gòu)建代理ip池的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 欧美一级美片在线观看免费 | 亚洲免费在线播放 | 高颜值美女啪啪 | 国产成人免费永久播放视频平台 | 高清不卡一区二区三区 | 亚洲视频在线免费看 | 最新福利片v国产片 | 久久久久久久综合色一本 | 免费看岛国视频在线观看 | 国产欧美综合精品一区二区 | 中文无码日韩欧免费视频 | 男女视频在线观看免费高清观看 | 99青青| 色偷偷在线刺激免费视频 | 国产亚洲精品自在久久77 | 国产午夜三级 | 欧美一级毛片欧美一级 | 免费一级成人免费观看 | 国产成人18黄网站在线观看网站 | 亚洲欧美在线一区二区 | 国产成人精品日本亚洲语音2 | 伊人婷婷色香五月综合缴激情 | 欧美午夜影院 | 欧美成人吃奶高清视频 | 欧美不卡视频在线观看 | 午夜毛片视频高清不卡免费 | 欧美在线黄色 | 国产精品久久久久久影院 | 99久久精品免费看国产免费软件 | 久草视频精品 | 欧美性欲视频 | 欧美成人一区二区三区在线视频 | 热er99久久6国产精品免费 | 台湾三级毛片 | 特级一级毛片免费看 | 欧美成人一级视频 | 欧美日本一道道一区二区三 | 国产乱理片在线观看夜 | 欧美三级一级片 | 九九国产 | 欧美日韩 国产区 在线观看 |