爬虫伪装代理IP
爬虫程序频繁访问某网站,很容易触发网站的保护机制,造成无法访问。本文将解决这一问题。
首先要伪装请求头,request默认是python-requests,emmm,这不是找事嘛,首先可以考虑改一下,然而,固定的还是容易被发现了,所以这里我用User-Agent随机生成。
But,仅仅伪装headers,使用随机 User-Agent来请求也会被发现,同一个ip地址,访问的次数太多,ip会被屏蔽,就用其他的ip继续去访问。这里有两种方案,一种是使用IP代理池,速度慢,能用的不多,所以这里我们使用开源库的ip代理池—异步async-proxy-pool。
下面详细介绍安装及用法。
0.伪装请求头-随机User-Agent
from fake_useragent import UserAgent # 下载:pip install fake-useragent
import requests
ua = UserAgent() # 实例化,需要联网但是网站不太稳定-可能耗时会长一些
headers = {
'User-Agent': ua.random # 伪装
}
url = 'https://www.baidu.com/'
response = requests.get(url, headers=headers)
print(response.status_code)
1. 安装Redis
Windows版:
-
进入官网:https://redis.io/
-
点击redis标志那一栏的Download下载:But官网没有Windows版本,进GitHub:https://github.com/MicrosoftArchive/redis
-
在release中下载需要的版本压缩包
-
解压后输入: redis-server.exe redis.windows.conf ,当看到显示6379端口即操作成功
-
运行时此窗口不要关闭。
Linus版本:
1.在线安装
直接输入命令 sudo apt-get install redis-server
安装完成后,Redis服务器会自动启动。
使用ps -aux|grep redis命令可以看到服务器系统进程默认端口6379
redis 2890 0.2 0.1 41872 6064 ? Ssl 14:17 0:07 /usr/bin/redis-server 127.0.0.1:6379
hzlarm 3222 0.0 0.0 11324 780 pts/2 S+ 15:02 0:00 grep --color=auto redis
使用netstat -nlt|grep 6379命令可以看到redis服务器状态
tcp 0 0 127.0.0.1:6379 0.0.0.0:* LISTEN
使用sudo /etc/init.d/redis-server status命令可以看到Redis服务器状态
-
宝塔安装
找到Redis……点一下安装即可
2. 安装ProxyPool
Windows版本:
- clone仓库
git clone https://github.com/Python3WebSpider/ProxyPool.git
-
打开项目中的 setting.py,在这里可以配置相关信息,比如 Redis 的地址密码相关
如果Redis 没有设置密码,此步跳过。
-
在你 clone 下来的文件目录中,安装相关所需的 python 模块
pip3 install -r requirements.txt
- redis保持开启
- 运行 run.py,(建议命令行运行或IDE运行们可以看到输出,Ctrl+C关闭)
- 访问http://localhost:5555/random可以得到代理IP
Linux版本:
git clone [email protected]:Python3WebSpider/ProxyPool.git (Python3.6以上)
通过docker安装
1. 安装docker (宝塔或pip)
2. 安装docker-compose (pip)
-
docker-compose up
https://github.com/Python3WebSpider/ProxyPool
普通安装
pip3 install -r requirements.txt
python3 run.py
我用的Python3.5,需要安装pip3
首先切换Python版本:https://blog.csdn.net/xbean1028/article/details/102482965