python - 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
解决方案
<a href="//detail.tmall.com/item.htm?id=612529092115&skuId=4486436443940&standard=1&user_id=2202421911399&cat_id=2&is_b=1&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'
推荐阅读
- python - 使用 Python 将对象列表作为池映射参数传递
- spring-boot - Spring Boot 应用程序能够在 Eclipse 环境中启动,但在带有快照的 Windows 命令行中运行时不能启动
- swift - 无法在 macOS 的 Swift 应用程序中请求日历事件访问(通过 EKEventStore)
- java - 与 io.swagger.v3.oas.models.OpenAPI 一起使用的 Swagger 注释的文档
- asp.net - 在 asp:repeater 中跳过一行/项目
- file - Lua 读取文件并写入新文件
- c++ - 返回二维数组的函数声明中的 3 个错误
- java - 即使调用者 Activity 被销毁,一个短时间运行的 Android 后台任务也可以安全地被忽略,这对吗?
- javascript - 如何修复有关 getelementbyid [Javascript] 的代码?
- python - 如何使用泊松分布计算列的预期值然后与实际值进行比较?