在scrapy脚本中,将空字段替换为0

2024-09-27 00:15:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编辑一个旧的潦草的脚本。对于某些页面,“Bathrooms”字段不存在。如果它不存在,我想输入一个“0”

我可以用pandas进行后期处理,但现在我想在scrapy脚本中实现这一点

我试过了,但有个错误

城镇。py“,第88行 其他: ^ 语法错误:无效语法

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

Tags: textpytxt脚本编辑pandasresponse错误
3条回答

编辑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")

看起来你可能把你的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

相关问题 更多 >

    热门问题