繁体   English   中英

Scrapy / Python:替换空字符串

[英]Scrapy/Python: Replace empty string

这是我的Scrapy搜寻器代码。 我正在尝试从网站中提取元数据值。 没有元数据在页面上出现多次。

class MySpider(BaseSpider):
    name = "courses"
    start_urls = ['http://www.example.com/listing']
    allowed_domains = ["example.com"]
    def parse(self, response):
     hxs = Selector(response)
    #for courses in response.xpath(response.body):
     for courses in response.xpath("//meta"):
     yield {
                'ScoreA': courses.xpath('//meta[@name="atarbur"]/@content').extract_first(),
                'ScoreB': courses.xpath('//meta[@name="atywater"]/@content').extract_first(),
                'ScoreC': courses.xpath('//meta[@name="atarsater"]/@content').extract_first(),
                'ScoreD': courses.xpath('//meta[@name="clearlywaur"]/@content').extract_first(),
               }
     for url in hxs.xpath('//ul[@class="scrapy"]/li/a/@href').extract():
      yield Request(response.urljoin(url), callback=self.parse)

因此,我要尝试实现的是,如果任何“分数”的值是一个空字符串(''),我想将其替换为0(零)。 我不确定如何在“ yield”块内添加条件逻辑。

任何帮助都非常感谢。

谢谢

extract_first()方法具有默认值的可选参数,但是在您的情况下,您可以使用or表达式:

foo = response.xpath('//foo').extract_first('').strip() or 0

在这种情况下,如果extract_first()返回一个没有任何文本的字符串,它将被评估为False,因此将采用evalution(0)的最新成员。

要将字符串类型转换为其他类型,请尝试:

foo = int(response.xpath('//foo').extract_first('').strip() or 0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM