【发布时间】:2013-02-26 08:34:25
【问题描述】:
我现在正在使用scrapy抓取网站,我需要设置代理处理已发送的请求。谁能帮我解决scrapy应用程序中的这个设置代理。如果您有,请也提供任何示例链接。我需要解决这个请求来自哪个 IP 的解决方案。
【问题讨论】:
标签: web-scraping
我现在正在使用scrapy抓取网站,我需要设置代理处理已发送的请求。谁能帮我解决scrapy应用程序中的这个设置代理。如果您有,请也提供任何示例链接。我需要解决这个请求来自哪个 IP 的解决方案。
【问题讨论】:
标签: web-scraping
您可以通过下面的代码找到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。
【讨论】: