python爬虫的思路及策略

回复
laical
崭露头角
崭露头角
帖子: 20
注册时间: 2020年03月26日 17:45
联系:

python爬虫的思路及策略

帖子 laical »

我们都知道做爬虫都不容易,爬虫在采集数据当中遇到的问题也很多。然后在采集过程中,遇到的某些问题,就需要做爬虫程序的相关优化。一般爬虫用户都会用亿牛云代理IP来解决很多问题。
这是一段被网站封IP的相关代码:
1673aa167d6a8953.webp.jpg
想要做好爬虫就要了解的爬虫的具体思路
1589336536157-bb9d45c3-c4c4-44b7-bfab-48ba615b5cb6 (1).png
爬虫的步骤一般分为:爬取、解析、储存、反爬
在采集互联网网站数据的同时,一定要做好网站反爬策略。一般的反爬策略就是使用亿牛云爬虫代理:
#! -*- encoding:utf-8 -*-
import base64
import sys
import random
PY3 = sys.version_info[0] >= 3
def base64ify(bytes_or_str):
if PY3 and isinstance(bytes_or_str, str):
input_bytes = bytes_or_str.encode('utf8')
else:
input_bytes = bytes_or_str
output_bytes = base64.urlsafe_b64encode(input_bytes)
if PY3:
return output_bytes.decode('ascii')
else:
return output_bytes
class ProxyMiddleware(object):
def process_request(self, request, spider):
# 代理服务器(产品官网 http://www.16yun.cn)
proxyHost = "t.16yun.cn"
proxyPort = "31111"
# 代理验证信息
proxyUser = "username"
proxyPass = "password"
request.meta['proxy'] = "http://{0}:{1}".format(proxyHost,proxyPort)
# 添加验证头
encoded_user_pass = base64ify(proxyUser + ":" + proxyPass)
request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass
# 设置IP切换头(根据需求)
tunnel = random.randint(1,10000)
request.headers['Proxy-Tunnel'] = str(tunnel)
class SplashProxyMiddleware(object):
def process_request(self, request, spider):
# 代理服务器(产品官网 http://www.16yun.cn)
proxyHost = "t.16yun.cn"
proxyPort = "31111"
# 代理验证信息
proxyUser = "username"
proxyPass = "password"
request.meta['splash']['args']['proxy'] = "http://{}:{}@{}:{}".format(proxyUser,proxyPass,proxyHost,proxyPort)
具体的爬虫策略,根据网站的反爬机制做相关优化,当然HTTP代理在爬虫过程中是必不可缺少的一部分。
回复

在线用户

正浏览此版面之用户: 没有注册用户 和 0 访客