我正在尝试为每个项目抓取一些额外的页面以获取一些位置信息。
在返回之前的项目末尾,我检查我们是否需要抓取额外的页面来获取信息,本质上这些页面包含一些位置详细信息,并且是一个简单的获取请求。
即 http://site.com.au/MVC/Offer/GetLocationDetails/?locationId=3761&companyId=206
上面的链接要么返回包含更多要抓取的页面的选择 - 要么返回包含地址详细信息的 dd/dt。无论哪种方式,我都需要提取此地址信息并将其附加到我的项目["位置"]
到目前为止,我有(在解析块的末尾)
return self.fetchLocations(locations_selector, company_id, item)
locations_selector包含位置 ID 列表
然后我有
def fetchLocations(self, locations, company_id, item): #response):
for location in locations:
if len(location)>1:
yield Request("http://site.com.au/MVC/Offer/GetLocationDetails/?locationId="+location+"&companyId="+company_id,
callback=self.parseLocation,
meta={'company_id': company_id, 'item': item})
最后
def parseLocation(self,response):
hxs = HtmlXPathSelector(response)
item = response.meta['item']
dl = hxs.select("//dl")
if len(dl)>0:
address = hxs.select("//dl[1]/dd").extract()
loc = {'address':remove_entities(replace_escape_chars(replace_tags(address[0], token=' '), replace_by=''))}
yield loc
locations_select = hxs.select("//select/option/@value").extract()
if len(locations_select)>0:
yield self.fetchLocations(locations_select, response.meta['company_id'], item)
似乎无法让这个工作....
这是你的代码:
def parseLocation(self,response):
hxs = HtmlXPathSelector(response)
item = response.meta['item']
dl = hxs.select("//dl")
if len(dl)>0:
address = hxs.select("//dl[1]/dd").extract()
loc = {'address':remove_entities(replace_escape_chars(replace_tags(address[0], token=' '), replace_by=''))}
yield loc
locations_select = hxs.select("//select/option/@value").extract()
if len(locations_select)>0:
yield self.fetchLocations(locations_select, response.meta['company_id'], item)
回调必须返回对其他页面或项目的请求。在上面的代码中,可以看到生成的请求,但不是项目。你有yield loc
,但loc
是一个dict
而不是Item
子类。