【问题标题】:Converting String of Ints and Floats to Individual Ints and Floats in a CSV将整数和浮点数字符串转换为 CSV 中的单个整数和浮点数
【发布时间】:2017-05-06 18:59:46
【问题描述】:

我正在使用 scrapy 来抓取股票上市前数据。以下是用于抓取网站的代码:

def parse(self, response):
    for sel in response.xpath('//body'):
        item = PremarketItem()
        item['volume'] = sel.xpath('//td[@class="tdVolume"]/text()').extract()
        item['last_price'] = sel.xpath('//div[@class="lastPrice"]/text()')[:30].extract()
        item['percent_change'] = sel.xpath(
        '//div[@class="chgUp"]/text()')[:15].extract() + sel.xpath('//div[@class="chgDown"]/text()')[:15].extract()
        item['ticker'] = sel.xpath('//a[@class="symbol"]/text()')[:30].extract()
        yield item

将以下代码输出到 .csv 文件中的内容大致如下:

ticker,percent_change,last_price,volume
"HTGM,SNCR,SAEX,IMMU,OLED,DAIO","27.43%,20.39%,17.28%,17.19%,15.69%","5,298350,700,1090000,76320,27190,13010",etc

如您所见,这些值被正确分隔,但它们都被困在大量字符串中。我尝试了多个 for 循环,但没有任何效果,而且我找不到任何东西。感谢您的帮助!

【问题讨论】:

    标签: string csv web-scraping scrapy


    【解决方案1】:

    您可以修复scrapy代码,而不是拆分大量字符串,以便首先将值分开。

    您的项目 XPath 以 // 选择与您的规范匹配的所有元素并因此在一个(大量)项目中输出所有元素开始。我想你的目标网站有一些关于目标项目的结构,例如表格行。

    然后,您需要找出与行匹配的 XPath 表达式并遍历这些行以解析每行一项。见以下伪代码:

    def parse(self, response):
    
        # Loop over table rows ... 
        for sel in response.xpath('//table/tr'):
    
            item = PremarketItem()
            # Use XPath starting in table row: Use dot at beginning
            item['volume'] = sel.xpath('./td[@class="tdVolume"]/text()').extract()
            # ... other fields ...
            yield item
    

    有关相对 XPath 表达式的示例,请参阅 scrapy documentation

    【讨论】:

      猜你喜欢
      • 2019-01-10
      • 2016-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 2014-04-29
      相关资源
      最近更新 更多