最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2020年09月22日 16:23:53   作者:亞洲小番茄  
這篇文章主要介紹了python爬蟲構(gòu)建代理ip池抓取數(shù)據(jù)庫的示例代碼,幫助大家更好的使用爬蟲,感興趣的朋友可以了解下

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

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

下面放上源代碼,并詳細注釋:

import requests
from lxml import etree
from requests.packages import urllib3
import random, time
 
urllib3.disable_warnings()
 
 
def spider(pages, max_change_porxies_times=300):
  """
  抓取 XiciDaili.com 的 http類型-代理ip-和端口號
 
  將所有抓取的ip存入 raw_ips.csv 待處理, 可用 check_proxies() 檢查爬取到的代理ip是否可用
  -----
  :param pages:要抓取多少頁
  :return:無返回
  """
  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)) # 每讀取一次頁面暫停一會,否則會被封
      if content.status_code == 503: # 如果503則ip被封,就更換ip
        proxies = get_proxies()
        try_times += 1
        print(f'第{str(try_times):0>3s}次變更,當前{proxies}')
        if try_times > max_change_porxies_times:
          print('超過最大嘗試次數(shù),連接失敗!')
          return -1
        continue
      else:
        break # 如果返回碼是200 ,就跳出while循環(huán),對爬取的頁面進行處理
 
    print(f'正在抓取第{i+1}頁數(shù)據(jù),共{pages}頁')
    for j in range(2, 102): # 用簡單的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'):
  """
  檢測給定的ip信息是否可用
 
  根據(jù)http,host,port組成proxies,對test_url進行連接測試,如果通過,則保存在 ips_pool.csv 中
  :param http: 傳輸協(xié)議類型
  :param host: 主機
  :param port: 端口號
  :param test_url: 測試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}檢測通過')
      with open('ips_pool.csv', 'a+') as f:
        f.write(','.join([http, host, port]) + '\n')
  except Exception as e: # 檢測不通過,就不保存,別讓報錯打斷程序
    print(e)
 
 
def check_local_ip(fn, test_url):
  """
  檢查存放在本地ip池的代理ip是否可用
 
  通過讀取fn內(nèi)容,加載每一條ip對test_url進行連接測試,鏈接成功則儲存在 ips_pool.csv 文件中
  :param fn: filename,儲存代理ip的文件名
  :param test_url: 要進行測試的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}檢測通過')
        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池獲得一個隨機的代理ip
  :param ip_pool_name: str,存放ip池的文件名,
  :return: 返回一個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('抓取完畢,時間:', t2 - t1)
 
  # check_local_ip('raw_ips.csv','http://www.baidu.com')

以上就是python爬蟲構(gòu)建代理ip池抓取數(shù)據(jù)庫的示例代碼的詳細內(nèi)容,更多關(guān)于python爬蟲構(gòu)建代理ip池的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

东平县| 南昌市| 开鲁县| 司法| 仲巴县| 南城县| 平利县| 闽清县| 星子县| 阳新县| 建平县| 新巴尔虎左旗| 克山县| 南川市| 渭南市| 宁津县| 朝阳区| 嘉义县| 井陉县| 内丘县| 武川县| 恩平市| 石城县| 邯郸市| 通江县| 和硕县| 叙永县| 阿图什市| 安龙县| 伊春市| 津市市| 宣化县| 锡林浩特市| 安阳市| 乌恰县| 莎车县| 呼伦贝尔市| 图们市| 灵丘县| 兴安盟| 晋江市|