【发布时间】:2018-01-07 18:31:34
【问题描述】:
我有一些带有“链接”属性的 JSON 文件。以下是这些文件的示例:
{
"links": [
"https://lastsecond.ir/hotels/1343-metropol-ankara",
"https://lastsecond.ir/hotels/1347-bianco-boutique"
],
"names": [
"Metropol Ankara hotel",
"Bianco Boutique hotel",
"Asal Ankara hotel",
.
.
.
}
我需要阅读所有这些文件,并为每个链接抓取页面并运行管道。有些文件只有一个链接,项目管道正确运行该文件,但对于具有多个链接的文件,项目管道只运行 JSON 文件的“链接”属性中的最后一个链接。 到目前为止,这是我的蜘蛛代码:
class HotelInfoSpider(scrapy.Spider):
def start_requests(self):
files = [f for f in listdir('lastsecond/hotels/') if isfile(join('lastsecond/hotels/', f))]
for file in files:
with open('lastsecond/hotels/' + file, 'r') as hotel_info:
hotel = json.load(hotel_info)
for link in hotel["links"]:
yield scrapy.Request(link, meta={'id': file})
name = 'hotel_info'
allowed_domains = ['lastsecond.ir']
custom_settings = {
'ITEM_PIPELINES': {
'lastsecond.pipelines.hotelFile': 400
}
}
def parse(self, response):
tour = ItemLoader(item=tourItem(), response=response)
tour.add_css('name', '.tours-list h5 a::text')
tour.add_css('nights', '.tours-list ul.mx-1 li:last-child label::text')
tour.add_value('found_date', str(datetime.now()))
tour.add_value('id', response.meta['id'])
yield tour.load_item()
这是我的管道代码:
class hotelFile(object):
def process_item(self, item, spider):
with open('lastsecond/results/' + item['id'][0], 'w') as result:
json.dump(dict(item), result)
return item
我也有另一个问题,在输出文件中,我只看到我用 add_value 分配的项目字段。我用add_css 分配的任何字段在输出文件中都不存在。
这是我在这段代码中的两个问题。
【问题讨论】:
-
请显示完整的代码并更正其格式。