python爬蟲設置代理ip

爬大量數據時候,如果一直使用一個ip,會被封禁。
因此要設置ip,在此我整理了一份ip代碼,原理是先獲取西刺代理的ip,然後進行篩選。每次返回一個。
供大家以及個人使用。
代碼如下:

# IP地址取自國內髙匿代理IP網站:http://www.xicidaili.com/nn/
# 僅僅爬取首頁IP地址就足夠一般使用
from bs4 import BeautifulSoup
import requests
import random
def get_ip_list(url, headers):
  web_data = requests.get(url, headers=headers)
  soup = BeautifulSoup(web_data.text, 'lxml')
  ips = soup.find_all('tr')
  ip_list = []
  for i in range(1, len(ips)):
    ip_info = ips[i]
    tds = ip_info.find_all('td')
    ip_list.append(tds[1].text + ':' + tds[2].text)
  return ip_list
def get_random_ip(ip_list):
  proxy_list = []
  for ip in ip_list:
    proxy_list.append('http://' + ip)
  proxy_ip = random.choice(proxy_list)
  proxies = {'http': proxy_ip}
  return proxies
if __name__ == '__main__':
  url = 'http://www.xicidaili.com/nn/'
  headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'
  }
  ip_list = get_ip_list(url, headers=headers)
  proxies = get_random_ip(ip_list)
  print(proxies)

(以上爲copy)
以上函數會返回一個代理ip。

main改成這個函數即可在你的代碼裏用:

def get_ip():

    url = 'http://www.xicidaili.com/nn/'
    ip_list = get_ip_list(url, headers=headers)
    proxies = get_random_ip(ip_list)
    return proxies

調用requests時候,如下即可。

web_data = requests.get(url, headers=headers, proxies=proxies)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章