【问题标题】:Exporting to CSV File导出为 CSV 文件
【发布时间】:2018-11-12 22:15:57
【问题描述】:

我正在尝试将此代码的结果导出到 CSV 文件。在代码之后,我在下面复制了 2 个结果。每只股票有 14 种商品,我想写入 CSV 文件,并为 14 种商品中的每一种提供一列,每只股票有一行。

import requests
from bs4 import BeautifulSoup

base_url = 'http://finviz.com/screener.ashx?v=152&s=ta_topgainers&o=price&c=0,1,2,3,4,5,6,7,25,63,64,65,66,67'
html = requests.get(base_url)
soup = BeautifulSoup(html.content, "html.parser")
main_div = soup.find('div', attrs = {'id':'screener-content'})
table = main_div.find('table')
sub = table.findAll('tr')
rows = sub[5].findAll('td')
for row in rows:
    link = row.a
    if link is not None:
        print(link.get_text())

这是结果的格式,每只股票 14 项/列。

PTN
Palatin Technologies, Inc.
Healthcare
Diagnostic Substances
USA
240.46M
9.22
193.43M
2.23M
0.76
1.19
7.21%
1,703,285
3
LKM
Link Motion Inc.
Technology
Application Software
China
128.95M
-
50.40M
616.76K
1.73
1.30
16.07%
1,068,798
4

试过这个,但无法让它工作。

TextWriter x = File.OpenWrite ("my.csv", ....);

x.WriteLine("Column1,Column2"); // header
x.WriteLine(coups.Cells[0].Text + "," + coups.Cells[1].Text);

【问题讨论】:

    标签: python web-scraping beautifulsoup export-to-csv


    【解决方案1】:

    为什么不使用内置的csv.writer

    【讨论】:

      【解决方案2】:

      这应该可行:

      import requests
      from bs4 import BeautifulSoup
      
      base_url = 'http://finviz.com/screener.ashx?v=152&s=ta_topgainers&o=price&c=0,1,2,3,4,5,6,7,25,63,64,65,66,67'
      html = requests.get(base_url)
      soup = BeautifulSoup(html.content, "html.parser")
      main_div = soup.find('div', attrs = {'id':'screener-content'})
      
      light_rows = main_div.find_all('tr', class_="table-light-row-cp")
      dark_rows = main_div.find_all('tr', class_="table-dark-row-cp")
      
      data = []
      for rows_set in (light_rows, dark_rows):
          for row in rows_set:
              row_data = []
              for cell in row.find_all('td'):
                  val = cell.a.get_text()
                  row_data.append(val)
              data.append(row_data)
      
      #   sort rows to maintain original order
      data.sort(key=lambda x: int(x[0]))
      
      import pandas
      pandas.DataFrame(data).to_csv("AAA.csv", header=False)
      

      这里有几件事:

      1. 我使用了“table-[light|dark]-row-cp”,因为所有行都有这些类之一(其他行都没有)
      2. 有两个独立的部分:一个是获取正确结构的数据,另一个是写入 CSV 文件。
      3. 我使用 pandas CSV 编写器,因为我对它很熟悉,但是当您有矩形数据(此处称为“数据”)时,您可以使用任何其他 CSV 编写器
      4. 您永远不应使用保留名称命名变量,例如“sub”或“link”:)

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 2017-03-12
        • 1970-01-01
        • 2013-12-26
        • 2023-01-20
        • 1970-01-01
        • 1970-01-01
        • 2021-01-23
        • 2014-05-12
        • 2019-04-18
        相关资源
        最近更新 更多