【发布时间】:2018-10-09 09:18:14
【问题描述】:
我想将 HTML 表格数据存储到 CSV 文件中。
我使用 python、selenium、BeautifulSoup、pandas、tabulate、numpy 编写了以下代码。
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd
from tabulate import tabulate
import numpy as np
#---Some code are here
datalist2 = []
for i in range(1, total+1):
xpath="/html/body/div[3]/table/tbody/tr/td[2]/div[2]/table/tbody/tr["+str(i)+"]/td[1]/a/img"
driver.find_element_by_xpath(xpath).click()
print("Open button " + str(i) + " Clicked")
soup_level2=BeautifulSoup(driver.page_source, 'lxml')
table2=soup_level2.find_all('table')[0]
df2=pd.read_html(str(table2),header=0)
datalist2.append(df2[0])
driver.execute_script("window.history.go(-1)")
print("moving_back_to_previous_page")
for i in range(len(datalist2)):
print(tabulate(datalist2[i]))
#text_file=open("output.csv","w")
#text_file.write(str(datalist2))
#text_file.close()
#print("report generated and saved")
#np.savetxt("output.csv", datalist2, delimiter=",", fmt='%s')
此代码print(tabulate(datalist2[i])) 在控制台中显示表格数据。
print(tabulate(datalist2[i])) 的示例输出
0 Date Crashed nan 2018-10-09 07:56:49 UTC
1 Date Reported nan 2018-10-09 07:56:57 UTC
2 Date Built nan 2018-06-06 01:26:35 UTC
3 Crash Reason nan SIGSEGV
4 Crash Addr nan 0x0
5 Dump file name nan 9556393da77a562fa086b0147a37106c6ff4bb76_mac14B7F66_dat2018-10-09-07-56-49_boxXB6_modC40COM_54dc2dd1-9abe-a568-1e3119e4-1908ccb0.dmp.tgz
此代码text_file.write(str(datalist2)) 将 datalist2 存储到 CSV 文件中。这段代码有问题。它不显示长文本。例如,索引 5 无法完整显示转储文件名。
text_file.write(str(datalist2))的示例输出
0 Date Crashed NaN 2018-10-09 07:56:49 UTC
1 Date Reported NaN 2018-10-09 07:56:57 UTC
2 Date Built NaN 2018-06-06 01:26:35 UTC
3 Crash Reason NaN SIGSEGV
4 Crash Addr NaN 0x0
5 Dump file name NaN 9556393da77a562fa086b0147a37106c6ff4bb76_mac14...
我还想删除索引列,第二列包含“nan”作为值。 我想将此数据存储到 CSV 文件中。 我该怎么做?
【问题讨论】:
标签: python pandas selenium numpy beautifulsoup