Scrapy&amp; ProxyMiddleware:蜘蛛错误处理<get http:=“”*****。com =“”>(referer:None)

时间:2015-11-12 14:33:18

标签: python proxy scrapy

我对Scrapy很陌生 - 非常感谢你的帮助。

问题的上下文:我尝试使用Scrapy 1.0.3和Python 2.7.10从网站抓取一些内容。此外,我正在使用代理 - 请参阅Scrapy and proxies。这是我的spider.py,middlewares.py和settings.py文件。

# spider.py

from scrapy import Spider
from scrapy.selector import Selector

from myproject.items import MyprojectItem


class MyprojectSpider(Spider):
name = "myproject"
allowed_domains = ["*****.com"]
start_urls = [l.strip() for l in open('urls.txt').readlines()]

def parse(self, response):
    stats = Selector(response).xpath(
        '//div[@id="stats"]/div[@class="some_content"]'
    )

    for stat in stats:
        item = MyprojectItem()
        item['path'] = stat.xpath(
            '//*[@id="stats"]/div//a/@href'
        ).extract()[2]
        item['rating'] = stat.xpath(
            '//span[@class="value"]/text()'
        ).extract()[0]
        item['count'] = stat.xpath(
            '//span[@class="count"]/text()'
        ).extract()[0]

        yield item


# middlewares.py

import base64

class ProxyMiddleware(object):
    def process_request(self, request,spider):
        request.meta['proxy'] = "http://host:port"
        proxy_user_pass = "user:password"
        encoded_user_pass = base64.encodestring(proxy_user_pass)
        request.headers['Proxy-Authorization'] = 'Basic ' + encoded_user_pass


# settings.py

BOT_NAME = 'myproject'

SPIDER_MODULES = ['myproject.spiders']
NEWSPIDER_MODULE = 'myproject.spiders'

DOWNLOADER_MIDDLEWARES ={
    'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 110,
    'middlewares.ProxyMiddleware': 100,
}

问题:我收到了“Spider错误处理”http://www.*****.com/*****/*****>(referer:None) “

2015-11-12 12:55:36 [scrapy] INFO: Scrapy 1.0.3 started (bot: myproject)
2015-11-12 12:55:36 [scrapy] INFO: Optional features available: ssl, http11
2015-11-12 12:55:36 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'myproject.spiders', 'CONCURRENT_REQUESTS_PER_DOMAIN': 32, 'CONCURRENT_REQUESTS': 32, 'SPIDER_MODULES': ['myproject.spiders'], 'BOT_NAME': 'myproject', 'DOWNLOAD_TIMEOUT': 600}
2015-11-12 12:55:36 [scrapy] INFO: Enabled extensions: CloseSpider, TelnetConsole, LogStats, CoreStats, SpiderState
2015-11-12 12:55:36 [scrapy] INFO: Enabled downloader middlewares: ProxyMiddleware, HttpAuthMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, DefaultHeadersMiddleware, MetaRefreshMiddleware, HttpCompressionMiddleware, RedirectMiddleware, CookiesMiddleware, ChunkedTransferMiddleware, DownloaderStats
2015-11-12 12:55:36 [scrapy] INFO: Enabled spider middlewares: HttpErrorMiddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddleware
2015-11-12 12:55:36 [scrapy] INFO: Enabled item pipelines: 
2015-11-12 12:55:36 [scrapy] INFO: Spider opened
2015-11-12 12:55:36 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2015-11-12 12:55:36 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2015-11-12 12:55:37 [scrapy] DEBUG: Crawled (200) <GET http://www.*****.com/*****/*****> (referer: None) ['partial']
2015-11-12 12:55:37 [scrapy] ERROR: Spider error processing <GET http://www.*****.com/*****/*****> (referer: None)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/defer.py", line 102, in iter_errback
yield next(it)
File "/usr/local/lib/python2.7/dist-packages/scrapy/spidermiddlewares/offsite.py", line 28, in process_spider_output
for x in result:
File "/usr/local/lib/python2.7/dist-packages/scrapy/spidermiddlewares/referer.py", line 22, in <genexpr>
return (_set_referer(r) for r in result or ())
File "/usr/local/lib/python2.7/dist-packages/scrapy/spidermiddlewares/urllength.py", line 37, in <genexpr>
return (r for r in result or () if _filter(r))
File "/usr/local/lib/python2.7/dist-packages/scrapy/spidermiddlewares/depth.py", line 54, in <genexpr>
return (r for r in result or () if _filter(r))
File "/home/*****/myproject/spiders/myproject_spider.py", line 28, in parse
stats = Selector(response).xpath(  
File "/usr/local/lib/python2.7/dist-packages/scrapy/selector/unified.py", line 80, in __init__
_root = LxmlDocument(response, self._parser)
File "/usr/local/lib/python2.7/dist-packages/scrapy/selector/lxmldocument.py", line 27, in __new__
cache[parser] = _factory(response, parser)
File "/usr/local/lib/python2.7/dist-packages/scrapy/selector/lxmldocument.py", line 13, in _factory
body = response.body_as_unicode().strip().encode('utf8') or '<html/>'
AttributeError: 'Response' object has no attribute 'body_as_unicode
2015-11-12 12:55:37 [scrapy] INFO: Closing spider (finished)
2015-11-12 12:55:37 [scrapy] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 292,
'downloader/request_count': 1,
'downloader/request_method_count/GET': 1,
'downloader/response_bytes': 172,
'downloader/response_count': 1,
'downloader/response_status_count/200': 1,
'finish_reason': 'finished',
'finish_time': datetime.datetime(2015, 11, 12, 12, 55, 37, 462225),
'log_count/DEBUG': 2,
'log_count/ERROR': 1,
'log_count/INFO': 7,
'response_received_count': 1,
'scheduler/dequeued': 1,
'scheduler/dequeued/memory': 1,
'scheduler/enqueued': 1,
'scheduler/enqueued/memory': 1,
'spider_exceptions/AttributeError': 1,
'start_time': datetime.datetime(2015, 11, 12, 12, 55, 36, 865505)}
2015-11-12 12:55:37 [scrapy] INFO: Spider closed (finished)

有任何建议吗?

1 个答案:

答案 0 :(得分:0)

问题可能在您的代码中的这一行:

stats = Selector(response).xpath(
        '//div[@id="stats"]/div[@class="some_content"]'
    )

带有文字selectors are constructed,但是您传递了整个响应对象,而是将其更改为响应正文:

stats = Selector(response.body).xpath(
        '//div[@id="stats"]/div[@class="some_content"]'
    )