所以这是我的 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)
所以我想要实现的是,如果任何 Scores 的值是空字符串 (''),我想用 0(零)替换它。我不确定如何在 'yield' 块中添加条件逻辑。
非常感谢任何帮助。
谢谢
extract_first()
方法具有默认值的可选参数,但是在您的情况下,您可以只使用or
表达式:
foo = response.xpath('//foo').extract_first('').strip() or 0
在这种情况下,如果extract_first()
返回一个没有任何文本的字符串,它将评估为`False,因此将采用 evaluation(0) 的最新成员。
要将字符串类型转换为其他类型,请尝试:
foo = int(response.xpath('//foo').extract_first('').strip() or 0)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句