避免在使用scrapy的网站上被禁止

时间:2015-06-12 14:29:46

标签: python web-scraping scrapy

我正在尝试从gsmarena下载数据。下载HTC one me规范的示例代码来自以下网站“http://www.gsmarena.com/htc_one_me-7275.php”,如下所述:

网站上的数据以表格和表格的形式分类。 数据格式为:

table header > td[@class='ttl'] > td[@class='nfo']

Items.py文件:

import scrapy

class gsmArenaDataItem(scrapy.Item):
    phoneName = scrapy.Field()
    phoneDetails = scrapy.Field()
    pass

蜘蛛锉:

from scrapy.selector import Selector
from scrapy import Spider
from gsmarena_data.items import gsmArenaDataItem

class testSpider(Spider):
    name = "mobile_test"
    allowed_domains = ["gsmarena.com"]
    start_urls = ('http://www.gsmarena.com/htc_one_me-7275.php',)

    def parse(self, response):
        # extract whatever stuffs you want and yield items here
        hxs = Selector(response)
        phone = gsmArenaDataItem()
        tableRows = hxs.css("div#specs-list table")
        for tableRows in tableRows:
            phone['phoneName'] = tableRows.xpath(".//th/text()").extract()[0]
            for ttl in tableRows.xpath(".//td[@class='ttl']"):
                ttl_value = " ".join(ttl.xpath(".//text()").extract())
                nfo_value = " ".join(ttl.xpath("following-sibling::td[@class='nfo']//text()").extract())
                colonSign = ": "
                commaSign = ", "
                seq = [ttl_value, colonSign, nfo_value, commaSign]
                seq = seq.join(seq)
        phone['phoneDetails'] = seq
        yield phone

然而,一旦我尝试使用以下方法在scrapy shell中加载页面,我就会被禁止:

"http://www.gsmarena.com/htc_one_me-7275.php"

我甚至尝试在settings.py。

中使用DOWNLOAD_DELAY = 3

请建议我该怎么做。

3 个答案:

答案 0 :(得分:5)

由于Scrapy的用户代理可能会发生这种情况。如您所见hereBOT_NAME变量用于撰写USER_AGENT。我的猜测是你要抓取的网站阻止了这一点。我试图查看他们的robots.txt file,但从那里得不到任何线索。

您可以尝试设置自定义UserAgent。在settings.py添加以下行:

USER_AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0"

实际上,您的USER_AGENT可能是anyone related to a browser

答案 1 :(得分:2)

如果网站显然根本不想被删除,那么设计一个新的解决方法只会推迟不可避免的事情 - 他们会制定一个新的规则来阻止你的新技巧,而你又回到原点。 / p>

与网站管理员交谈 - 除非他们只是为了让其他人(如某些商业实体那样)努力工作,否则他们可能会有一个很好的替代方案,例如您可以订阅的API或(付费?)Feed到。

答案 2 :(得分:2)

添加到"设置真实用户代理并伪装成真正的浏览器"故事,这是我在github上传的中间件:

它基于fake-useragent package,并根据实际浏览器使用统计信息为每个请求使用不同的随机User-Agent标头。

此外,请确保您没有违反网站的任何规则或使用条款。另见:

相关问题