爬虫的新手使用教程(python代理IP)
前言
Python爬虫要经历爬虫、爬虫被限制、爬虫反限制的过程。当然后续还要网页爬虫限制优化,爬虫再反限制的一系列道高一尺魔高一丈的过程。爬虫的初级阶段,添加headers和ip代理可以解决很多问题。
PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行获取http://t.cn/A6Zvjdun
本人自己在爬取豆瓣读书的时候,就以为爬取次数过多,直接被封了IP.后来就研究了代理IP的问题.
(当时不知道什么情况,差点心态就崩了...),下面给大家介绍一下我自己代理IP爬取数据的问题,请大家指出不足之处.
问题
这是我的IP被封了,一开始好好的,我还以为是我的代码问题了
思路:
从网上查找了一些关于爬虫代理IP的资料,得到下面的思路
- 爬取一些IP,过滤掉不可用.
- 在requests的请求的proxies参数加入对应的IP.
- 继续爬取.
- 收工
- 好吧,都是废话,理论大家都懂,上面直接上代码...
思路有了,动手起来.
运行环境
Python 3.7, Pycharm
这些需要大家直接去搭建好环境...
准备工作
- 爬取IP地址的网站(国内高匿代理)
- 校验IP地址的网站
- 你之前被封IP的py爬虫脚本...
上面的网址看个人的情况来选取
爬取IP的完整代码
PS:简单的使用bs4获取IP和端口号,没有啥难度,里面增加了一个过滤不可用IP的逻辑
关键地方都有注释了
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是否可以用.
为什么要这样判断?
主要是虽然上面经过了过滤,但是不代表在你爬取的时候是可以用的,所以还是得多做一个判断.
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)
为什么选择国内高匿代理!
总结
使用这样简单的代理IP,基本上就可以应付在爬爬爬着被封IP的情况了.而且没有使用自己的IP,间接的保护?!?!
大家有其他的更加快捷的方法,欢迎大家可以拿出来交流和讨论,谢谢。
爬虫的新手使用教程(python代理IP)的更多相关文章
- Python爬虫教程-11-proxy代理IP,隐藏地址(猫眼电影)
Python爬虫教程-11-proxy代理IP,隐藏地址(猫眼电影) ProxyHandler处理(代理服务器),使用代理IP,是爬虫的常用手段,通常使用UserAgent 伪装浏览器爬取仍然可能被网 ...
- python爬虫之反爬虫(随机user-agent,获取代理ip,检测代理ip可用性)
python爬虫之反爬虫(随机user-agent,获取代理ip,检测代理ip可用性) 目录 随机User-Agent 获取代理ip 检测代理ip可用性 随机User-Agent fake_usera ...
- Python爬虫常用小技巧之设置代理IP
设置代理IP的原因 我们在使用Python爬虫爬取一个网站时,通常会频繁访问该网站.假如一个网站它会检测某一段时间某个IP的访问次数,如果访问次数过多,它会禁止你的访问.所以你可以设置一些代理服务器来 ...
- Python爬虫实战——反爬策略之代理IP【无忧代理】
一般情况下,我并不建议使用自己的IP来爬取网站,而是会使用代理IP. 原因很简单:爬虫一般都有很高的访问频率,当服务器监测到某个IP以过高的访问频率在进行访问,它便会认为这个IP是一只"爬虫 ...
- Python 爬虫练习(一) 爬取国内代理ip
简单的正则表达式练习,爬取代理 ip. 仅爬取前三页,用正则匹配过滤出 ip 地址和 端口,分别作为key.value 存入 validip 字典. 如果要确定代理 ip 是否真的可用,还需要再对代理 ...
- python——代理ip获取
python爬虫要经历爬虫.爬虫被限制.爬虫反限制的过程.当然后续还要网页爬虫限制优化,爬虫再反限制的一系列道高一尺魔高一丈的过程. 爬虫的初级阶段,添加headers和ip代理可以解决很多问题. 贴 ...
- PYTHON代理IP
import urllib.request url = 'http://www.whatismyip.com.tw/' proxy_support = urllib.request.ProxyHand ...
- Scrapy爬取美女图片第三集 代理ip(上) (原创)
首先说一声,让大家久等了.本来打算那天进行更新的,可是一细想,也只有我这样的单身狗还在做科研,大家可能没心思看更新的文章,所以就拖到了今天.不过忙了521,522这一天半,我把数据库也添加进来了,修复 ...
- Python 爬虫的代理 IP 设置方法汇总
本文转载自:Python 爬虫的代理 IP 设置方法汇总 https://www.makcyun.top/web_scraping_withpython15.html 需要学习的地方:如何在爬虫中使用 ...
随机推荐
- kali的安装详解--摘自官方
官方网址:https://www.kali.org/docs/virtualization/install-vmware-workstation-player-kali-guest-vm/ 在VMwa ...
- Mysql性能优化:为什么要用覆盖索引?
导读 相信读者看过很多MYSQL索引优化的文章,其中有很多优化的方法,比如最佳左前缀,覆盖索引等方法,但是你真正理解为什么要使用最佳左前缀,为什么使用覆盖索引会提升查询的效率吗? 本篇文章将从MYSQ ...
- CF1326A Bad Ugly Numbers 题解
原题链接 简要题意: 构造一个长为 \(n\) 的数,使得每位均不为 \(0\),且 \(n\) 不被它的各位数字整除. 比方说, \(n = 239\) 是合法的.因为: \(2 \not | 23 ...
- nmap端口扫描工具安装和使用方法
nmap(Network Mapper)是一款开源免费的针对大型网络的端口扫描工具,nmap可以检测目标主机是否在线.主机端口开放情况.检测主机运行的服务类型及版本信息.检测操作系统与设备类型等信息. ...
- jupyter notebook 中同时添加Python2和3,在conda下配置R语言运行的环境
1.第一步,安装Python2的环境 首先,在安装anaconda的时候先选择一个Python安装,我先安装的是Python3 然后,在anaconda Prompt下创建Python2环境 现在,还 ...
- arcgis server10.7修改打印模板后前台调用不生效
在10.5.1及之前的版本中,如果更改打印地图模板,如字体设置,那么直接修改[ArcGIS for Server 安装目录]/Templates/ExportWebMapTemplates下的mxd的 ...
- js数据类型及方法
数据类型及方法 数据类型 number 不区分整数和浮点数 string 字符串 boolean true / false 布尔 object null 数组 function 函数 undefine ...
- JVM tomcat 性能调优
1,新建web 测试项目并且发布到Tomcat,访问路径:http://127.0.0.1:8080/JvmWeb/index @WebServlet("/index") publ ...
- macbook中出现2003 - Can't connect to MySQL server on '127.0.0.1' (61 "Connection refused") 如何解决
第一步 关闭mysql服务: 苹果->系统偏好设置->最下边点mysql 在弹出页面中 关闭mysql服务(点击stop mysql server) 如果这种方法没有成功: 可以使用命令行 ...
- jdbc连接方法
jdbc(Java Database Connectivity)的5个步骤: 一.加载驱动. 反射中的主动加载,Driver.class右键copy qualified Name 二.创建连接 dat ...