首页 > 解决方案 > 导出为 CSV 文件

问题描述

我正在尝试将此代码的结果导出到 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);

标签: pythonweb-scrapingbeautifulsoupexport-to-csv

解决方案


这应该有效:

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' :)

希望有帮助。


推荐阅读