[使用案例]怎么使用ip代理來(lái)爬蟲Python?
你可能會(huì)覺得怎么爬蟲那么復(fù)雜,經(jīng)常IP就被網(wǎng)站封了,還得去找ip代理來(lái)使用才可以繼續(xù)爬蟲。這是由于網(wǎng)站對(duì)于自己服務(wù)器以及信息的一種保護(hù)。
Python爬蟲要經(jīng)歷爬蟲、爬蟲被限制、爬蟲反限制的過(guò)程。當(dāng)然后續(xù)還要網(wǎng)頁(yè)爬蟲限制優(yōu)化,爬蟲再反限制的一系列道高一尺魔高一丈的過(guò)程。爬蟲的初級(jí)階段,添加headers和ip代理可以解決很多問(wèn)題。
下面我們跟著IP海,來(lái)看看Python抓取ip代理的具體代碼操作:
運(yùn)行環(huán)境:
Python 3.7, Pycharm
這些需要大家直接去搭建好環(huán)境...
準(zhǔn)備工作:
爬取IP地址的網(wǎng)站(國(guó)內(nèi)高匿代理)
爬取IP的完整代碼:
PS:簡(jiǎn)單的使用bs4獲取IP和端口號(hào),沒有啥難度,里面增加了一個(gè)過(guò)濾不可用IP的邏輯,以下關(guān)鍵地方都有注釋了。
#!/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):
"""請(qǐng)求html頁(yè)面信息"""
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):
"""檢測(cè)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
# 檢測(cè)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()
當(dāng)然了,以上這些只是用ip代理爬蟲的常規(guī)操作,爬蟲大神可能已經(jīng)對(duì)于這些已經(jīng)見怪不怪了。大家如果需要選擇好用不貴的爬蟲ip代理,歡迎咨詢IP海。
版權(quán)聲明:本文為IP海(iphai.cn)原創(chuàng)作品,未經(jīng)許可,禁止轉(zhuǎn)載!
Copyright © www.wibm.ac.cn. All Rights Reserved. IP海 版權(quán)所有.
IP海僅提供中國(guó)內(nèi)IP加速服務(wù),無(wú)法跨境聯(lián)網(wǎng),用戶應(yīng)遵守《服務(wù)條款》內(nèi)容,嚴(yán)禁用戶使用IP海從事任何違法犯罪行為。
鄂ICP備19030659號(hào)-3
鄂公網(wǎng)安備42100302000141號(hào)
計(jì)算機(jī)軟件著作權(quán)證
ICP/EDI許可證:鄂B2-20200106