Python代理IP爬虫的新手使用教程


Posted in Python onSeptember 05, 2019

前言

Python爬虫要经历爬虫、爬虫被限制、爬虫反限制的过程。当然后续还要网页爬虫限制优化,爬虫再反限制的一系列道高一尺魔高一丈的过程。爬虫的初级阶段,添加headers和ip代理可以解决很多问题。

本人自己在爬取豆瓣读书的时候,就以为爬取次数过多,直接被封了IP.后来就研究了代理IP的问题.

(当时不知道什么情况,差点心态就崩了...),下面给大家介绍一下我自己代理IP爬取数据的问题,请大家指出不足之处.

问题

这是我的IP被封了,一开始好好的,我还以为是我的代码问题了

Python代理IP爬虫的新手使用教程

思路:

从网上查找了一些关于爬虫代理IP的资料,得到下面的思路

  1. 爬取一些IP,过滤掉不可用.
  2. 在requests的请求的proxies参数加入对应的IP.
  3. 继续爬取.
  4. 收工
  5. 好吧,都是废话,理论大家都懂,上面直接上代码...

思路有了,动手起来.

运行环境

Python 3.7, Pycharm

这些需要大家直接去搭建好环境...

准备工作

  1. 爬取IP地址的网站(国内高匿代理)
  2. 校验IP地址的网站
  3. 你之前被封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()

使用方法完整代码

PS: 主要是通过使用随机的IP来爬取,根据request_status来判断这个IP是否可以用.

为什么要这样判断?

主要是虽然上面经过了过滤,但是不代表在你爬取的时候是可以用的,所以还是得多做一个判断.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2018/11/22 
# @Author : liangk
# @Site :
# @File : get_douban_books.py
# @Software: PyCharm

from bs4 import BeautifulSoup
import datetime
import requests
import json
import random

ip_random = -1
article_tag_list = []
article_type_list = []


def get_html(url):
 header = {
  'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36'
 }
 global ip_random
 ip_rand, proxies = get_proxie(ip_random)
 print(proxies)
 try:
  request = requests.get(url=url, headers=header, proxies=proxies, timeout=3)
 except:
  request_status = 500
 else:
  request_status = request.status_code
 print(request_status)
 while request_status != 200:
  ip_random = -1
  ip_rand, proxies = get_proxie(ip_random)
  print(proxies)
  try:
   request = requests.get(url=url, headers=header, proxies=proxies, timeout=3)
  except:
   request_status = 500
  else:
   request_status = request.status_code
  print(request_status)
 ip_random = ip_rand
 request.encoding = 'gbk'
 html = request.content
 print(html)
 return html


def get_proxie(random_number):
 with open('ip.txt', 'r') as file:
  ip_list = json.load(file)
  if random_number == -1:
   random_number = random.randint(0, len(ip_list) - 1)
  ip_info = ip_list[random_number]
  ip_url_next = '://' + ip_info['address'] + ':' + ip_info['port']
  proxies = {'http': 'http' + ip_url_next, 'https': 'https' + ip_url_next}
  return random_number, proxies


# 程序主入口
if __name__ == '__main__':
 """只是爬取了书籍的第一页,按照评价排序"""
 start_time = datetime.datetime.now()
 url = 'https://book.douban.com/tag/?view=type&icn=index-sorttags-all'
 base_url = 'https://book.douban.com/tag/'
 html = get_html(url)
 soup = BeautifulSoup(html, 'lxml')
 article_tag_list = soup.find_all(class_='tag-content-wrapper')
 tagCol_list = soup.find_all(class_='tagCol')

 for table in tagCol_list:
  """ 整理分析数据 """
  sub_type_list = []
  a = table.find_all('a')
  for book_type in a:
   sub_type_list.append(book_type.text)
  article_type_list.append(sub_type_list)

 for sub in article_type_list:
  for sub1 in sub:
   title = '==============' + sub1 + '=============='
   print(title)
   print(base_url + sub1 + '?start=0' + '&type=S')
   with open('book.text', 'a', encoding='utf-8') as f:
    f.write('\n' + title + '\n')
    f.write(url + '\n')
   for start in range(0, 2):
    # (start * 20) 分页是0 20 40 这样的
    # type=S是按评价排序
    url = base_url + sub1 + '?start=%s' % (start * 20) + '&type=S'
    html = get_html(url)
    soup = BeautifulSoup(html, 'lxml')
    li = soup.find_all(class_='subject-item')
    for div in li:
     info = div.find(class_='info').find('a')
     img = div.find(class_='pic').find('img')
     content = '书名:<%s>' % info['title'] + ' 书本图片:' + img['src'] + '\n'
     print(content)
     with open('book.text', 'a', encoding='utf-8') as f:
      f.write(content)

 end_time = datetime.datetime.now()
 print('耗时: ', (end_time - start_time).seconds)

为什么选择国内高匿代理!

Python代理IP爬虫的新手使用教程

总结

使用这样简单的代理IP,基本上就可以应付在爬爬爬着被封IP的情况了.而且没有使用自己的IP,间接的保护?!?!

大家有其他的更加快捷的方法,欢迎大家可以拿出来交流和讨论,谢谢。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对三水点靠木的支持。

Python 相关文章推荐
Python遍历zip文件输出名称时出现乱码问题的解决方法
Apr 08 Python
python通过opencv实现批量剪切图片
Nov 13 Python
使用Python实现微信提醒备忘录功能
Dec 04 Python
Python读取指定日期邮件的实例
Feb 01 Python
python操作日志的封装方法(两种方法)
May 23 Python
Python使用scrapy爬取阳光热线问政平台过程解析
Aug 14 Python
基于python实现文件加密功能
Jan 06 Python
python3实现将json对象存入Redis以及数据的导入导出
Jul 16 Python
python飞机大战游戏实例讲解
Dec 04 Python
Python中的np.argmin()和np.argmax()函数用法
Jun 02 Python
利用python实时刷新基金估值(摸鱼小工具)
Sep 15 Python
Python matplotlib可视化之绘制韦恩图
Feb 24 Python
关于Python内存分配时的小秘密分享
Sep 05 #Python
python global关键字的用法详解
Sep 05 #Python
python requests证书问题解决
Sep 05 #Python
Python使用scipy模块实现一维卷积运算示例
Sep 05 #Python
Python图像处理模块ndimage用法实例分析
Sep 05 #Python
Pycharm+django2.2+python3.6+MySQL实现简单的考试报名系统
Sep 05 #Python
PyCharm搭建Spark开发环境的实现步骤
Sep 05 #Python
You might like
也谈截取首页新闻 - 范例
2006/10/09 PHP
PHP输出当前进程所有变量/常量/模块/函数/类的示例
2013/11/07 PHP
php发送http请求的常用方法分析
2016/11/08 PHP
THinkPHP获取客户端IP与IP地址查询的方法
2016/11/14 PHP
PHP自动识别当前使用移动终端
2018/05/21 PHP
laravel-admin 中列表筛选方法
2019/10/03 PHP
PHP Beanstalkd消息队列的安装与使用方法实例详解
2020/02/21 PHP
jQuery带箭头提示框tooltips插件集锦
2014/11/17 Javascript
Angularjs实现分页和分页算法的示例代码
2016/12/23 Javascript
vue中promise的使用及异步请求数据的方法
2018/11/08 Javascript
微信小程序上线发布流程图文详解
2019/05/06 Javascript
nodejs对mongodb数据库的增加修删该查实例代码
2020/01/05 NodeJs
JQuery事件冒泡和默认行为代码实例
2020/05/13 jQuery
vue-router 2.0 跳转之router.push()用法说明
2020/08/12 Javascript
[03:39]DOTA2英雄梦之声_第05期_幽鬼
2014/06/23 DOTA
用python代码做configure文件
2014/07/20 Python
python实现自动更换ip的方法
2015/05/05 Python
python操作mongodb根据_id查询数据的实现方法
2015/05/20 Python
TensorFlow实现简单卷积神经网络
2018/05/24 Python
详解Python 定时框架 Apscheduler原理及安装过程
2019/06/14 Python
python用win32gui遍历窗口并设置窗口位置的方法
2019/07/26 Python
在python中利用dict转json按输入顺序输出内容方式
2020/02/27 Python
性能服装:HYLETE
2018/08/14 全球购物
Omio俄罗斯:一次搜索公共汽车、火车和飞机的机票
2018/11/17 全球购物
银河香水:Galaxy Perfume
2019/03/25 全球购物
海量信息软件测试笔试题
2015/08/08 面试题
体育系毕业生求职自荐信
2014/04/16 职场文书
啦啦队口号大全
2014/06/16 职场文书
2014年社区居委会主任重阳节讲话稿
2014/09/25 职场文书
圣诞晚会主持词开场白
2015/05/28 职场文书
矛盾论读书笔记
2015/06/29 职场文书
校园运动会广播稿
2015/08/19 职场文书
vue3如何优雅的实现移动端登录注册模块
2021/03/29 Vue.js
Go语言操作数据库及其常规操作的示例代码
2021/04/21 Golang
Redis入门教程详解
2021/08/30 Redis
JavaScript中10个Reduce常用场景技巧
2022/06/21 Javascript