Scrapy:加载带有变量项目

x8diyxa7  于 2022-11-23  发布在  其他
关注(0)|答案(2)|浏览(87)

你好,我是新来的,我需要加载两个日期在一个网站上。我如何把变量在项目?

fecha_today = datetime.date.today().strftime("%d-%m-%y")
fecha_yesterday = (datetime.date.today()- timedelta(1)).strftime("%d-%m-%y")

我的蜘蛛

def parse_date(self, response):
    self.log("\n\n\n ponemos las fechas \n\n\n")
    hxs = HtmlXPathSelector(response)

    link_fecha = hxs.select('/html/body/table/tbody/tr[3]/td/a')
    date_item=  ItemLoader ( FechaItem ()) 
    date_item.add_path('fecha_today','/html/body/table[1]/tbody/tr[2]/td/form/table/tbody/tr[3]/td[1]/span/input')
    date_item.add_path('fecha_yesterday','/html/body/table[1]/tbody/tr[2]/td/form/table/tbody/tr[4]/td[1]/span/input')

    return date_item.load_item()

我必须在www.example.com中输入什么item.py才能让变量带我去呢?item.py

class    FechaLoader(scrapy.loader.ItemLoader):

我需要把这些变量放到一个表中
enter image description here

pgpifvop

pgpifvop1#

根本不需要使用项目加载程序
我已经用Python Scrapy编码3年多了,我从来没有用过它,只是简单地生成一个这样的字典

def parse_date(self, response):
    self.log("\n\n\n ponemos las fechas \n\n\n")
    item = {}

    item['fecha_today'] = response.xpath('/html/body/table[1]/tbody/tr[2]/td/form/table/tbody/tr[3]/td[1]/span/input').extract_first()
    item['fecha_yesterday'] = response.xpath('/html/body/table[1]/tbody/tr[2]/td/form/table/tbody/tr[4]/td[1]/span/input').extract_first()

    yield item
w41d8nur

w41d8nur2#

我刚刚遇到这个问题。所以我们需要把变量放到itemLoader字段中。我们可以通过ItemLoader对象的add_value方法给itemLoader添加值。下面是代码。

fecha_today = datetime.date.today().strftime("%d-%m-%y")
fecha_yesterday = (datetime.date.today()- timedelta(1)).strftime("%d-%m-%y")

def parse_date(self, response):
self.log("\n\n\n ponemos las fechas \n\n\n")
hxs = HtmlXPathSelector(response)

link_fecha = hxs.select('/html/body/table/tbody/tr[3]/td/a')
date_item=  ItemLoader ( FechaItem ()) 
date_item.add_value('fecha_today', str(fecha_today))
date_item.add_value('fecha_yesterday',str(fecha_yesterday))

return date_item.load_item()

相关问题