Python 导出为CSV文件

Python 导出为CSV文件,python,web-scraping,beautifulsoup,export-to-csv,Python,Web Scraping,Beautifulsoup,Export To Csv,我正在尝试将此代码的结果导出到CSV文件。在代码之后,我复制了下面的两个结果。每个股票有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' h

我正在尝试将此代码的结果导出到CSV文件。在代码之后,我复制了下面的两个结果。每个股票有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]-rowcp”,因为intrest的所有行都有一个这样的类(其他行都没有)
  • 有两个独立的部分:一个是以正确的结构获取数据,另一个是编写CSV文件
  • 我使用了pandas CSV编写器,因为我对它很熟悉,但当您有矩形数据(此处称为“数据”)时,您可以使用任何其他CSV编写器
  • 永远不要使用保留名称命名变量,如“sub”或“link”:
  • 希望有帮助