首页 > 解决方案 > Scrapy 没有获得完整的产品名称,用逗号替换某些字符?

问题描述

我正在使用scrapy在中国电子商务网站天猫上获取产品名称和价格。代码非常简单,但是当它抓取名称时,它会将产品名称的某些部分替换为逗号。对于下面的示例,我输入了“ipad air 3”,第一个产品的名称是“Apple/苹果 10.5 英寸 iPad Air”。“10.5英寸iPad Air”部分以不同的颜色显示,我认为是因为它与搜索关键字匹配。但我不确定为什么scrapy 会在产品名称的那部分得到“,,,,”。有谁知道我可以尝试修复它的潜在方法?

综上所述,我想要得到的结果是“Apple/苹果 10.5 英寸 iPad air”;但是,我得到的结果是“Apple/Apple ', ' ', ' ', ' ', '”。这是屏幕截图: 我得到的网页结果

items = TmallspiderItem()
product_info = response.css('.product-iWrap')

for product in product_info:
    product_name = product.css('.productTitle a::text').extract()
    product_price = product.css('.productPrice em::text').extract()
    items['product_name'] = product_name
    items['product_price'] = product_price
    yield items

标签: pythonscrapy

解决方案


<a href="//detail.tmall.com/item.htm?id=612529092115&amp;skuId=4486436443940&amp;standard=1&amp;user_id=2202421911399&amp;cat_id=2&amp;is_b=1&amp;rn=c9a973f4c51d2bf839339810354ff07a" target="_blank" title="Apple/苹果 Apple/苹果 10.5 英寸 iPad Air" data-p="8-11" >
Apple/苹果 Apple/苹果 <span class=H>10.5</span> <span class=H>英寸</span> <span class=H>iPad</span> <span class=H>Air</span>
</a>

如您所见,您尝试获取的名称是跨多个span元素拆分的。
您的 css 选择器仅选择作为元素的直接子节点的文本节点a,因此它不会获取这些节点的内容。

您可以修改选择器以获取所有后代并加入这些后代,但我建议改用normalize-space()xpath 函数。

>>> product.css('.productTitle a::text').extract()
['\nApple/苹果 ', ' ', ' ', ' ', '\n']
>>> product.css('.productTitle a ::text').extract()
['\nApple/苹果 ', '10.5', ' ', '英寸', ' ', 'iPad', ' ', 'Air', '\n']
>>> product.css('.productTitle a').xpath('normalize-space()').get()
'Apple/苹果 10.5 英寸 iPad Air'

推荐阅读