4

主题。我们的蜘蛛跟踪链接并使用“解析页面”函数解析它们,该函数返回项目。在第一次调用 parse_page 之前,如何为每个请求添加不同的代理?

例如,我有 250 个代理池,并希望随机选择每个代理请求。

4

1 回答 1

4

您可以为此创建一些中间件。例如:

#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://123.456.789.012"

    # Use the following lines if your proxy requires authentication
    proxy_user_pass = "USER_AND_PASS"

    # setup basic authentication for the proxy
    encoded_user_pass = base64.encodestring(proxy_user_pass)
    request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass

我相信您可以通过修改上述代码轻松地随机化代理 url、用户名和密码。如果您需要任何其他帮助,请告诉我。

于 2012-12-03T23:06:26.853 回答