1 回答

TA贡献1911条经验 获得超7个赞
如果您删除 XPath 上的索引,它们将找到页面中的所有项目:
response.xpath('//*[@id="content"]/div/div/ul/li/a/h3').extract() # Returns 7 items
但是,您应该注意到这将返回所选 html 元素的字符串列表。如果您想要元素内的文本,您应该添加/text()XPath。(这看起来像你做的)
另外,你只得到一个回报的原因是因为你在将所有项目分配给时将它们连接成一个字符串item:
items['product_name'] = ''.join(title).strip()
这title是一个元素列表,您将它们全部连接在一个字符串中。相同的逻辑适用于其他变量
如果那真的是您想要的,您可以忽略以下内容,但我相信更好的方法是分别执行 for 循环和yield它们?
我的建议是:
def parse(self, response):
products = response.xpath('//*[@id="content"]/div/div/ul/li')
for product in products:
items = ShopItem()
items['product_name'] = product.xpath('a/h3/text()').get()
items['product_sale_price'] = product.xpath('a/span/del/span/text()').get()
items['product_original_price'] = product.xpath('a/span/ins/span/text()').get()
items['product_category'] = product.xpath('a/span/ins/span/text()').get()
yield items
请注意,在您的原始代码中,您的categoryvar 与您的 具有相同的 XPath product_original_price,我将逻辑保留在代码中,但这可能是一个错误。
添加回答
举报