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

Python使用requests xpath 并開啟多線程爬取西刺代理ip實例

 更新時間:2020年03月06日 13:13:38   作者:haeasringnar  
這篇文章主要介紹了Python使用requests xpath 并開啟多線程爬取西刺代理ip實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

我就廢話不多說啦,大家還是直接看代碼吧!

import requests,random
from lxml import etree
import threading
import time

angents = [
  "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
  "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
  "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
  "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
  "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
  "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
  "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
  "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
  "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
  "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
  "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
  "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
  "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
  "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
  "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
]

def get_all_xici_urls(start_num,stop_num):
  xici_urls = []
  for num in range(start_num,len(stop_num)+1):
    xici_http_url = 'http://www.xicidaili.com/wt/'
    xici_http_url += str(num)
    xici_urls.append(xici_http_url)
  print('獲取所有待爬取xici url 已完成...')
  return xici_urls
def get_all_http_ip(xici_http_url,headers,proxies_list):
  try:
    all_ip_xpath = '//table//tr/child::*[2]/text()'
    all_prot_xpath = '//table//tr/child::*[3]/text()'
    response = requests.get(url=xici_http_url,headers=headers)
    html_tree = etree.HTML(response.text)
    ip_list = html_tree.xpath(all_ip_xpath)
    port_list = html_tree.xpath(all_prot_xpath)
    # print(ip_list)
    # print(prot_list)
    new_proxies_list = []
    for index in range(1,len(ip_list)):
      # print('http://{}:{}'.format(ip_list[index],port_list[index]))
      proxies_dict = {}
      proxies_dict['http'] = 'http://{}:{}'.format(str(ip_list[index]),str(port_list[index]))
      new_proxies_list.append(proxies_dict)
    proxies_list += new_proxies_list
    return proxies_list
  except Exception as e:
    print('發(fā)生了錯誤:url為 ',xici_http_url,'錯誤為 ',e)

if __name__ == '__main__':
  start_num = int(input('請輸入起始頁面:').strip())
  stop_num = int(input('請輸入結(jié)束頁面:').strip())
  print('開始爬取...')
  t_list = []
  # 容納需要使用的西刺代理ip
  proxies_list = []
  # 使用多線程
  xici_urls = get_all_xici_urls(start_num,stop_num)
  for xici_get_url in xici_urls:
    #隨機篩選一個useragent
    headers = {'User-Agent': random.choice(angents)}
    t = threading.Thread(target=get_all_http_ip,args=(xici_get_url,headers,proxies_list))
    t.start()
    t_list.append(t)
  for j in t_list:
    j.join()
  print('所有需要的代理ip已爬取完成...')
  print(proxies_list)
  print(len(proxies_list))

補充知識:python爬取xici的免費代理、并驗證(重點、清楚)

網(wǎng)上爬取xici的帖子很多,但是驗證都說的不是很清楚,這里我會認(rèn)真給大家解釋

這里我寫了一個代理類proxy,寫了四個方法(個人寫法不必在意),get_user_agent(得到隨機use-agent,請求頭中最重要的一個)、get_proxy(爬取代理IP)、test_proxy(驗證代理可用性)、store_txt(將可用的代理保存到txt文件中。

1.爬?。篽eaders是請求頭,choice是可以選擇是爬取Http代理還是https代理,first、end為開始和結(jié)束的頁碼(結(jié)束不包含最后一頁)

 def get_proxy(self, headers, choice='http', first=1, end=2):
    """
    獲取代理
    :param choice:
    :param first: 開始爬取的頁數(shù)
    :param end: 結(jié)束爬取的后一頁
    :return:
    """
 
    ip_list = []
    base_url = None
    
    # 選擇爬取的網(wǎng)站,一個是http、一個是https的
    if choice == 'http':
      base_url = 'http://www.xicidaili.com/wt/'
    elif choice == 'https':
      base_url = 'http://www.xicidaili.com/wn/'
    
    # 控制頁碼用正則匹配,并將爬取的IP和端口號用:鏈接
    for n in range(first, end):
      actual_url = base_url + str(n)
      html = requests.get(url=actual_url, headers=headers).text
      pattern = '(\d+\.\d+\.\d+\.\d+)</td>\s*<td>(\d+)'
      re_list = re.findall(pattern, html)
 
      for ip_port in re_list:
        ip_port = ip_port[0] + ':' + ip_port[1]
        ip_list.append(ip_port)
    return ip_list

2. 驗證:網(wǎng)上大部分是用request直接請求一個網(wǎng)址看是否通過或者看狀態(tài)碼是否是200, 但是有一個問題是即使你設(shè)置了代理IP??赡軙ㄟ^,但通過的不是用你設(shè)置的代理IP而是用你自己公網(wǎng)下的IP(大部分時候我們用ifconfig查詢的是我們所在局域網(wǎng)下的IP,及私網(wǎng)IP)。

linux下你可以用這些命令的其中任何一個查看你的公網(wǎng)IP:

curl icanhazip.com
curl ifconfig.me
curl curlmyip.com
curl ip.appspot.com
curl ipinfo.io/ip
curl ipecho.net/plain
curl www.trackip.net/i

注意:那這樣要怎么辦,其實我們可以向上述命令一樣先用你爬下的代理IP訪問 http://icanhazip.com/, 它可以返回你電腦發(fā)送請求時的公網(wǎng)IP(此時如果你設(shè)置代理IP了就會是返回你所發(fā)送請求的代理IP),然后你將它爬取下來(直接獲取返回的值的文本就可以了),并和你發(fā)送請求時的代理IP作比較,如果不相等說明此代理IP不能用,因為雖然你設(shè)置了代理Ip,但是電腦在你代理IP請求不同的情況下,直接又使用了你公網(wǎng)的IP去請求,當(dāng)然成功了,但不代表你的代理IP可以用。如果相等,那就證明此網(wǎng)站就是你所用的代理IP訪問請求成功的,所以此IP可用。

def test_proxy(self, ip_port, choice='http'):
    """
    測試代理是否能用
    :param ip_port:
    :param choice:
    :return:
    """
    proxies = None
 
    # 這個網(wǎng)站可以返回你公網(wǎng)下的IP,如果你加代理請求后,返回的就是你代理的IP(這樣做是防止你雖然用的是代理IP,但實際是用你自己的公網(wǎng)IP訪問的請求)
    tar_url = "http://icanhazip.com/"
 
    # 獲取隨機User-agent
    user_agent = self.get_user_agent()
 
    # 將user-agent放在headers中
    headers = {'User-Agent': user_agent}
 
    # 選擇驗證的是http、還是https
    if choice == 'http':
      proxies = {
        "http": "http://"+ip_port,
      }
 
    elif choice == 'https':
      proxies = {
        "https": "https://" + ip_port,
      }
 
    try:
      # 將IP從IP和端口號連起來的分出來
      thisIP = "".join(ip_port.split(":")[0:1])
      res = requests.get(tar_url, proxies=proxies, headers=headers, timeout=8)
 
      # 爬取下來返回的值,一定要用strip去除空格
      proxyIP = res.text.strip()
      
      # 三個狀態(tài),如過直接通不過,那就返回false,如果通過但是不是代理的IP,也返回false
      if proxyIP == thisIP:
        return proxyIP
      else:
        return False
    except:
      return False

最后附上整段代碼:

import requests
import re
import random
import codecs
from urllib import parse
 
 
class proxy:
  """
  代理類
  """
  def __init__(self):
    pass
 
  def get_user_agent(self):
    """
    得到隨機user-agent
    :return:
    """
    user_agents = [
      "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
      "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
      "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
      "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
      "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
      "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
      "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
      "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
      "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
      "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
      "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
      "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
      "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
      "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
      "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
      "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
      "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
      "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
      "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
      "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
      "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)",
      "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
      "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
      "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
      "Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
      "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
      "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
      "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10"
    ]
    user_agent = random.choice(user_agents)
    return user_agent
 
 
  def get_proxy(self, headers, choice='http', first=1, end=2):
    """
    獲取代理
    :param choice:
    :param first: 開始爬取的頁數(shù)
    :param end: 結(jié)束爬取的后一頁
    :return:
    """
 
    ip_list = []
    base_url = None
    if choice == 'http':
      base_url = 'http://www.xicidaili.com/wt/'
    elif choice == 'https':
      base_url = 'http://www.xicidaili.com/wn/'
 
    for n in range(first, end):
      actual_url = base_url + str(n)
      html = requests.get(url=actual_url, headers=headers).text
      pattern = '(\d+\.\d+\.\d+\.\d+)</td>\s*<td>(\d+)'
      re_list = re.findall(pattern, html)
 
      for ip_port in re_list:
        ip_port = ip_port[0] + ':' + ip_port[1]
        ip_list.append(ip_port)
    return ip_list
 
 
  def test_proxy(self, ip_port, choice='http'):
    """
    測試代理是否能用
    :param ip_port:
    :param choice:
    :return:
    """
    proxies = None
    # 這個網(wǎng)站可以返回你公網(wǎng)下的IP,如果你加代理請求后,返回的就是你代理的IP(這樣做是防止你雖然用的是代理IP,但實際是用你自己的公網(wǎng)IP訪問的請求)
    tar_url = "http://icanhazip.com/"
    user_agent = self.get_user_agent()
    headers = {'User-Agent': user_agent}
    if choice == 'http':
      proxies = {
        "http": "http://"+ip_port,
      }
 
    elif choice == 'https':
      proxies = {
        "https": "https://" + ip_port,
      }
    try:
      thisIP = "".join(ip_port.split(":")[0:1])
      res = requests.get(tar_url, proxies=proxies, headers=headers, timeout=8)
      proxyIP = res.text.strip()
      if proxyIP == thisIP:
        return proxyIP
      else:
        return False
    except:
      return False
 
  def store_txt(self, choice='http', first=1, end=2):
    """
    將測試通過的ip_port保存為txt文件
    :param choice:
    :param first:
    :param end:
    :return:
    """
    user_agent = self.get_user_agent()
    headers = {'User-Agent': user_agent}
    ip_list = self.get_proxy(headers=headers, choice=choice, first=first, end=end)
    with codecs.open("Http_Agent.txt", 'a', 'utf-8') as file:
      for ip_port in ip_list:
        ip_port = self.test_proxy(ip_port, choice=choice)
        print(ip_port)
        if ip_port:
          file.write('\'' + ip_port + "\'\n")

以上這篇Python使用requests xpath 并開啟多線程爬取西刺代理ip實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 關(guān)于keras中的Reshape用法

    關(guān)于keras中的Reshape用法

    這篇文章主要介紹了關(guān)于keras中的Reshape用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • Python中常用操作字符串的函數(shù)與方法總結(jié)

    Python中常用操作字符串的函數(shù)與方法總結(jié)

    這篇文章主要介紹了Python中常用操作字符串的函數(shù)與方法總結(jié),包括字符串的格式化輸出與拼接等基礎(chǔ)知識,需要的朋友可以參考下
    2016-02-02
  • pytorch 使用單個GPU與多個GPU進(jìn)行訓(xùn)練與測試的方法

    pytorch 使用單個GPU與多個GPU進(jìn)行訓(xùn)練與測試的方法

    今天小編就為大家分享一篇pytorch 使用單個GPU與多個GPU進(jìn)行訓(xùn)練與測試的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • plotly分割顯示mnist的方法詳解

    plotly分割顯示mnist的方法詳解

    這篇文章主要為大家詳細(xì)介紹了plotly分割顯示mnist的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • Python中8種運算符介紹以及示例

    Python中8種運算符介紹以及示例

    在Python編程中運算符是用于執(zhí)行各種操作的特殊符號或關(guān)鍵字,下面這篇文章主要給大家介紹了關(guān)于Python中8種運算符介紹以及示例的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2024-02-02
  • Python淺拷貝與深拷貝用法實例

    Python淺拷貝與深拷貝用法實例

    這篇文章主要介紹了Python淺拷貝與深拷貝用法,實例分析了Python淺拷貝與深拷貝的功能與使用方法,需要的朋友可以參考下
    2015-05-05
  • Python使用psutil庫實現(xiàn)系統(tǒng)監(jiān)控與管理詳解

    Python使用psutil庫實現(xiàn)系統(tǒng)監(jiān)控與管理詳解

    在我們的測試工作中,監(jiān)控和管理系統(tǒng)資源是一項重要的任務(wù),本文將介紹如何使用psutil庫來實現(xiàn)系統(tǒng)監(jiān)控和管理,以及一些實用的技巧和示例,希望對大家有所幫助
    2022-10-10
  • Python?中?Pandas?文件操作和讀取?CSV?參數(shù)詳解

    Python?中?Pandas?文件操作和讀取?CSV?參數(shù)詳解

    CSV?又稱逗號分隔值文件,是一種簡單的文件格式,以特定的結(jié)構(gòu)來排列表格數(shù)據(jù),這篇文章主要介紹了Python?之?Pandas?文件操作和讀取?CSV?參數(shù)詳解,需要的朋友可以參考下
    2023-03-03
  • Python實現(xiàn)批量合并圖片到word文檔

    Python實現(xiàn)批量合并圖片到word文檔

    這篇文章主要為大家詳細(xì)介紹了如何利用Python實現(xiàn)批量合并指定文件夾中的所有圖片并插入到Word文檔中并保存,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-10-10
  • Python全棧之學(xué)習(xí)JS(2)

    Python全棧之學(xué)習(xí)JS(2)

    這篇文章主要為大家介紹了Python全棧之JS,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-01-01

最新評論

河曲县| 东辽县| 鱼台县| 盱眙县| 泰兴市| 讷河市| 沁阳市| 阳泉市| 奉节县| 蓬安县| 靖西县| 溧水县| 三明市| 岳西县| 烟台市| 胶州市| 西畴县| 永平县| 平安县| 陇南市| 冀州市| 平阳县| 遂溪县| 闸北区| 江源县| 民权县| 托克托县| 政和县| 常山县| 囊谦县| 上栗县| 博白县| 平山县| 郧西县| 岗巴县| 民丰县| 海口市| 深水埗区| 益阳市| 鲜城| 廉江市|