sách gpt4 ai đã đi

python - 垃圾/ python : Replace empty string

In lại 作者:太空宇宙 更新时间:2023-11-04 09:59:54 28 4
mua khóa gpt4 Nike

这是我的 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” block 中添加条件逻辑。

非常感谢任何帮助。

Cảm ơn

1 Câu trả lời

extract_first() 方法有一个默认值的可选参数,但是在您的情况下,您可以只使用 hoặc 表达式:

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

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

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

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

关于python - 垃圾/ python : Replace empty string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44128611/

28 4 0
太空宇宙
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com