我正在尝试使用带有 scrapy 的中间件,所以在我名为“Tutorial”的项目中我已经这样做了:
在我添加的设置文件中:
DOWNLOADER_MIDDLEWARES = {
'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 110,
'tutorial.middlewares.ProxyMiddleware': 100,
}
同时创建一个名为 middlewares.py 的文件,其中包含以下内容:
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'] = "39.179.187.48:8123"
当我尝试在 shell 中运行项目时
scrapy shell http://google.com
我收到以下错误:
file "/usr/local/lib/python2.7/dist-packages/twisted/internet/threads.py", line 122, in blockingCallFromThread
result.raiseException()
File "<string>", line 2, in raiseException
TypeError: argument of type 'NoneType' is not iterable
请您参考如下方法:
根据documentation :
process_request()should either: return None, return a Response object, return a Request object, or raise IgnoreRequest.
您没有从自定义中间件的 process_request() 方法返回:
class ProxyMiddleware(object):
def process_request(self, request, spider):
request.meta['proxy'] = "39.179.187.48:8123"
return request
返回 request 假设你想用 proxy 集重新安排请求。
