[英]Replace empty fields with 0 in scrapy script
我正在編輯一個舊的 scrapy 腳本。 對於某些頁面,“浴室”字段不存在。 如果它不存在,我想輸入一個“0”。
我可以使用 pandas 發布處理,但現在我想在 scrapy 腳本中實現這一點。
我試試這個,但得到錯誤..
town.py”,第 88 行 else: ^ SyntaxError: invalid syntax
bathrooms_txt = response.xpath(".//dt[contains(text(), 'Bathrooms')]/following-sibling::dd/text()").extract_first()
if bathrooms_txt == "":
bathrooms = "0"
else:
bathrooms = bathrooms_txt
except:
pass
看起來你可能弄亂了你的 try 語句。
你的意思是說:
bathrooms_txt = response.xpath(".//dt[contains(text(), 'Bathrooms')]/following-sibling::dd/text()").extract_first()
try:
if bathrooms_txt == "":
bathrooms = "0"
else:
bathrooms = bathrooms_txt
except:
pass
編輯 piplines.py
def process_item(self, item, spider):
if item.get('bathrooms_txt') is none:
item['bathrooms_txt'] = "0"
extract_first
方法具有可用於這種情況的default
參數:
value = response.xpath("selector").extract_first(default="0")
或者:
value = response.xpath("selector").extract_first("0")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.