【问题标题】:How to write to CSV file without using terminal in webscraper如何在不使用 webscraper 终端的情况下写入 CSV 文件
【发布时间】:2018-06-13 02:02:03
【问题描述】:

我需要一些帮助。我的刮刀现在正在运行,它会创建 items.csv 文件,但只将 product_name 等放入其中......我该如何解决这个问题? 这是我的代码:

import scrapy
import csv

class ProductSetSpider(scrapy.Spider):
name = "Product_spider"
start_urls = ['https://www.grainger.com/category/bacharach/ecatalog/N-1z125ev']
FEED_URI= r"C:\Users\Owner\Desktop\scraperProject\ScraperProject\items.csv"
# custom_settings = {'FEED_EXPORT_FIELDS': ["product_name" , ],
# }
def parse(self, response):
    self.log('I just visited' + response.url)
    yield {
        'product_name': response.css('h2.list-view__product-heading::text').extract()
        #'product_detail' : response.css('').extract_first()
        #'product_rating' : response.css('').extract_first()
        #'product_category' : response.css('').extract_first()
        #'product_company' : response.css('').extract_first()
        }

    Output_file = open('items.csv', 'w') #items.csv is name of output file
    fieldnames = ['product_name', 'product_details', 'product_rating', 'product_category', 'product_company'] #adding header to file
    writer = csv.DictWriter(Output_file, fieldnames=fieldnames)
    writer.writeheader()
    for url in start_urls:
        writer.writerow({product_name: response.url(fieldnames, css)}) #writing data into file.
        file_name.close()

【问题讨论】:

  • 你有两个同名的函数。重命名一个并向我们展示他们是如何被调用的。
  • 您好,感谢您的评论。我记得把它扔在那里只是为了看看它是否会让它运行并且它确实运行了,但我并没有真正有理由启动另一个功能。我把它编辑了。

标签: python scrapy export-to-csv scraper


【解决方案1】:

在你的蜘蛛集的 settings.py 或 custom_settings 属性中

FEED_URI="location/csvfilename.csv"

https://doc.scrapy.org/en/latest/topics/feed-exports.html

【讨论】:

  • Yash,你能说得更具体一点吗?我需要创建一个 settings.py 并只使用那行代码吗?或者我应该在我的 scraper.py 文件中设置 feed_uri="location"
  • 如果您使用的是scrapy项目,那么它会在模块根目录中,或者您也可以在custom_settings属性中设置它
  • custom_settings = { 'FEED_URI': "location/products.csv" } 没关系
  • 我想我没有使用 scrapy 项目,因为我的目录中除了我的 scraper.py 之外没有任何其他内容。生病尝试添加 custom_settings 属性。这应该包含在我的导入之后的类中还是类语句之前?
  • @BenP。是的,它需要在你的蜘蛛类中,无论你在问题中写了什么都是定义 custom_settings 的正确方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 2015-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 2014-11-29
相关资源
最近更新 更多