我正在尝试从 gsmarena 下载数据。下载 HTC one me spec 的示例代码来自以下站点“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。
请建议我应该怎么做。
最佳答案
这可能是因为 Scrapy 的用户代理。如你所见here ,BOT_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
关于python - 避免在使用 scrapy 的网站上被禁止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30805566/