我现在正在使用scrapy来抓取网站我需要设置代理处理已发送的请求。任何人都可以帮助我在scrapy应用程序中解决此设置代理。如果您有,也请提供任何示例链接。我需要解决方案来处理此请求的IP。
答案 0 :(得分:6)
您可以通过以下代码找到here:
1 - 创建一个名为middlewares.py
的新文件并将其保存在scrapy项目中,并将以下代码添加到其中。
# Importing base64 library because we'll need it ONLY
#in case if the proxy we are going to use requires authentication
import base64
# Start your middleware class
class ProxyMiddleware(object):
# overwrite process request
def process_request(self, request, spider):
# Set the location of the proxy
request.meta['proxy'] = "http://YOUR_PROXY_IP:PORT"
# Use the following lines if your proxy requires authentication
proxy_user_pass = "USERNAME:PASSWORD"
# setup basic authentication for the proxy
encoded_user_pass = base64.encodestring(proxy_user_pass)
request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass
2 - 打开项目的配置文件(./project_name/settings.py)并添加以下代码
DOWNLOADER_MIDDLEWARES = {
'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 110,
'project_name.middlewares.ProxyMiddleware': 100,
}
此外,您可以使用scrapy
的多个代理。更多信息可以
找到here。