Python爬蟲換動態ip代理代碼
簡單爬蟲經常IP就被網站封了,爬不到想爬的內容,還得去找ip代理來使用才可以繼續爬蟲。這是由于網站對于自己服務器以及信息的一種保護。
Python爬蟲要經歷爬蟲、爬蟲被限制、爬蟲反限制的過程。當然后續還要網頁爬蟲限制優化,爬蟲再反限制的一系列道高一尺魔高一丈的過程。爬蟲的初級階段,添加headers和ip代理可以解決很多問題。
下面我們來看看Python抓取ip代理的具體代碼操作:
運行環境:
Python 3.7, Pycharm
這些需要大家直接去搭建好環境...
準備工作:
爬取IP地址的網站(國內高匿代理)
Python爬蟲取IP的完整代碼:PS:簡單的使用bs4獲取IP和端口號,沒有啥難度,里面增加了一個過濾不可用IP的邏輯,以下關鍵地方都有注釋了。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2018/11/22
# @Author : liangk
# @Site :
# @File : auto_archive_ios.py
# @Software: PyCharm
import requests
from bs4 import BeautifulSoup
import json
class GetIp(object):
"""抓取ip代理"""
def __init__(self):
"""初始化變量"""
self.url = 'http://www.xicidaili.com/nn/'
self.check_url = 'https://www.ip.cn/'
self.ip_list = []
@staticmethod
def get_html(url):
"""請求html頁面信息"""
header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' }
try:
request = requests.get(url=url, headers=header)
request.encoding = 'utf-8'
html = request.text
return html
except Exception as e:
return ''
def get_available_ip(self, ip_address, ip_port):
"""檢測IP地址是否可用"""
header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' }
ip_url_next = '://' + ip_address + ':' + ip_port
proxies = {'http': 'http' + ip_url_next, 'https': 'https' + ip_url_next}
try:
r = requests.get(self.check_url, headers=header, proxies=proxies, timeout=3)
html = r.text
except: print('fail-%s' % ip_address)
else:
print('success-%s' % ip_address)
soup = BeautifulSoup(html, 'lxml')
div = soup.find(class_='well')
if div:
print(div.text)
ip_info = {'address': ip_address, 'port': ip_port}
self.ip_list.append(ip_info)
def main(self):
"""主方法"""
web_html = self.get_html(self.url)
soup = BeautifulSoup(web_html, 'lxml')
ip_list = soup.find(id='ip_list').find_all('tr')
for ip_info in ip_list:
td_list = ip_info.find_all('td')
if len(td_list) > 0:
ip_address = td_list[1].text
ip_port = td_list[2].text
# 檢測IP地址是否有效
self.get_available_ip(ip_address, ip_port)
# 寫入有效文件
with open('ip.txt', 'w') as file:
json.dump(self.ip_list, file)
print(self.ip_list)
# 程序主入口
if __name__ == '__main__':
get_ip = GetIp()
get_ip.main()
當然了,以上這些只是用ip代理爬蟲的常規操作,爬蟲大神可能已經對于這些已經見怪不怪了。