Python代理IP爬虫的新手使用教程-创新互联
前言

Python爬虫要经历爬虫、爬虫被限制、爬虫反限制的过程。当然后续还要网页爬虫限制优化,爬虫再反限制的一系列道高一尺魔高一丈的过程。爬虫的初级阶段,添加headers和ip代理可以解决很多问题。
本人自己在爬取豆瓣读书的时候,就以为爬取次数过多,直接被封了IP.后来就研究了代理IP的问题.
(当时不知道什么情况,差点心态就崩了...),下面给大家介绍一下我自己代理IP爬取数据的问题,请大家指出不足之处.
问题
这是我的IP被封了,一开始好好的,我还以为是我的代码问题了

思路:
从网上查找了一些关于爬虫代理IP的资料,得到下面的思路
- 爬取一些IP,过滤掉不可用.
- 在requests的请求的proxies参数加入对应的IP.
- 继续爬取.
- 收工
- 好吧,都是废话,理论大家都懂,上面直接上代码...
思路有了,动手起来.
运行环境
Python 3.7, Pycharm
这些需要大家直接去搭建好环境...
准备工作
- 爬取IP地址的网站(国内高匿代理)
- 校验IP地址的网站
- 你之前被封IP的py爬虫脚本...
上面的网址看个人的情况来选取
爬取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()另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
网页标题:Python代理IP爬虫的新手使用教程-创新互联
转载来于:http://www.jxjierui.cn/article/psseh.html


咨询
建站咨询
