python - Scrapy CSV 文件格式不正确
问题描述
基本上,我将提取的这些数据放入 csv 文件中,但格式存在一些问题。
- 首先只显示零件,其他没有显示 fg。数量和价格 - 其次,列标题似乎重复了行。
我希望将零件、价格、数量显示在不同的列中,并且标题将是名称。如果有人能告诉我在哪里可以学习这样做,那将有很大帮助!
name = 'digi'
allowed_domains = ['digikey.com']
custom_settings = {
"USER_AGENT": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
}
start_urls = ['https://www.digikey.com/products/en/integrated-circuits-ics/memory/774?FV=-1%7C428%2C-8%7C774%2C7%7C1&quantity=0&ColumnSort=0&page=1&k=cy621&pageSize=500&pkeyword=cy621']
def parse(self, response):
data={}
parts=response.css('Table#productTable.productTable')
for part in parts:
for p in part.css('tbody#lnkPart'):
yield {
'Part': p.css('td.tr-mfgPartNumber span::text').extract(),
'Quantity': p.css('td.tr-minQty.ptable-param span.desktop::text').extract(),
'Price': p.css('td.tr-unitPrice.ptable-param span::text').extract()
}
设置
BOT_NAME = 'website1'
SPIDER_MODULES = ['website1.spiders']
NEWSPIDER_MODULE = 'website1.spiders'
#Export as CSV Feed
#FEED_EXPORT_FIELDS: ["parts", "quantity", "price"]
FEED_FORMAT = "csv"
FEED_URI = "parts.csv"
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'website1 (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
解决方案
当您在 Scrapy shell 中进行测试时,您是否获得了正确的数据?在将它们提交到脚本之前,值得在scrapy shell 中试用你的选择器。
我没有详细查看您的 CSS 选择器,但是有很多 for 循环,基本上您需要做的就是遍历 tr。因此,找到一个 CSS 选择器来获取所有行而不是遍历整个表并按照自己的方式向下工作可能更有效。
更新:
既然你问了 for 循环
for p in response.css('tbody#lnkPart > tr'):
yield {
'Part': p.css('td.tr-mfgPartNumber span::text').get(),
'Quantity': p.css('td.tr-minQty.ptable-param span.desktop::text').get(),
'Price': p.css('td.tr-unitPrice.ptable-param span::text').get()
}
请注意,我们只需要在 tr 周围循环,这会选择所有这些。get() 方法仅选择具有特定 tr 的项目。
请注意,您需要考虑如何处理空间和无项目。值得仔细考虑这部分并想出一种简单的方法来修改结果。
更新代码
def parse(self, response):
for p in response.css('tbody#lnkPart > tr'):
if p.css('td.tr-minQty.ptable-param span.desktop::text').get():
quantity = p.css('td.tr-minQty.ptable-param span.desktop::text').get()
quantity = quantity.strip()
cleaned_quantity = int(quantity.replace(',',''))
else:
quantity = 'No quantity'
if p.css('td.tr-unitPrice.ptable-param span::text').get():
price = p.css('td.tr-unitPrice.ptable-param span::text').get()
cleaned_price = price.strip()
else:
price = 'No Price'
yield {
'Part': p.css('td.tr-mfgPartNumber span::text').get(),
'Quantity': cleaned_quantity,
'Price': cleaned_price
}
推荐阅读
- java - 日志在 Elastic Beanstalk Tomcat 环境中不起作用
- node.js - 部署到谷歌应用引擎中的服务后无法得到任何响应
- serenity-platform - 宁静网格不翻译查找编辑器
- latex - 一个 LaTex 文件生成两个 PDF 文件
- javascript - PouchDB 无法将 blob 转换为图像 src 的 url
- sql - 查找匹配列 - SQL 或 Excel 公式无宏,在哪里找到匹配
- html - CSS BUG:箭头进度条高度不匹配
- java - AAPT:错误:“6495ed”与属性背景 (attr) 参考不兼容|颜色
- php - php artisan 迁移错误 - 找不到驱动程序
- android - 将给定的数组插入新的长度