python - 导出为 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);
解决方案
这应该有效:
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)
这里有几件事:
- 我使用了“table-[light|dark]-row-cp”,因为所有行都有这些类之一(并且没有其他行有它们)
- 有两个单独的部分:一个是以正确的结构获取数据,另一个是写入 CSV 文件。
- 我使用 pandas CSV 编写器,因为我很熟悉它,但是当您有矩形数据(此处称为“数据”)时,您可以使用任何其他 CSV 编写器
- 您永远不应该使用保留名称命名变量,例如 'sub' 或 'link' :)
希望有帮助。
推荐阅读
- wordpress - 如何修复 WooCommerce/Printful 集成错误?
- python - 如何在不使用列表的情况下在 Cython 中定义扩展类型的对象数组?
- python - Precision-Recall 曲线与 ROC 曲线:我是否仍应通过 SMOTE 将 PR 曲线应用于已经平衡的信息?
- c# - 无法登录天蓝色机器人并获取令牌
- pyomo - Pyomo 目标定义错误:“SyntaxError:生成器表达式必须用括号括起来”
- android - android BottomNavigationView 下划线项
- angular - 为什么出现服务工作者 javascript 而不是 index.html
- centos7 - firewall-cmd tcp ssh REJECT 规则不起作用
- excel - 如果有 2 个连续的空行,则删除行
- python - 在python中使用下划线作为循环变量是否可以接受?