[英]Can i dynamicaly create keys for dict in python?
我正在 Scrapy 中創建一個蜘蛛。 我想以這種方式刮桌子:
<tr>
<th>
作為鍵,使用<td>
作為內容我想出的代碼是這樣的。
def parse(self, response):
item = {}
item['code'] = response.xpath('//meta[@itemprop="sku"]/@content').extract_first()
tables = response.css('.technical-specs')
for table in tables:
specs = tables.xpath('tbody/tr')
for s in specs:
key = s.xpath('th/text()').extract_first().replace(" ", "_").replace("(", "_").replace(")", "_").replace("/", "").lower()
value = s.xpath('td/text()').extract_first()
item[key] = value
return item
但它不起作用。 這有可能實現嗎?
您需要創建一個 dict 實例,然后在循環內添加項目。 例如:
my_dict = dict() # Can be {} to
for item in items:
key = item.key
value = item.value
my_dict[key] = value
Regards
我的問題詳細信息中更新了解析 function 的現在工作代碼。 問題不在於循環或字典的實現方式,而在於我如何提取數據。 我正在使用.extract()這使得響應 unicode 和“不可回收”。 Remove.extract 是解決方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.