[英]I'm trying to get web scraped data to print in excel side by side instead of vertically
I have scraped 2 data sets from a webpage and imported it to an xls file. 我从网页上抓取了2个数据集,并将其导入到xls文件中。 \\n allows me to re-run my program and print the data under the old data, but I would like to print the new data in the column next to the old data.
\\ n允许我重新运行程序并在旧数据下打印数据,但是我想在旧数据旁边的列中打印新数据。
It pastes like this: 它像这样粘贴:
Old data (new row) New data 旧数据(新行)新数据
I would like it to paste like this: 我想要这样粘贴:
Old data (new column) New data 旧数据(新列)新数据
I have tried using both \\t and \\n in my codes current format. 我曾尝试以我的代码当前格式同时使用\\ t和\\ n。 I'm not sure if I have the arrangement wrong or if there's a different \\command.
我不确定我的安排是否错误或是否有其他\\ command。
def main():
import csv
import os
from selenium import webdriver
ticker = input("Enter your ticker: ")
url = "http://financials.morningstar.com/cash-flow/cf.html?t=" + ticker.upper()
print(url)
browser = webdriver.Firefox()
browser.get(url)
values_elementticker = browser.find_elements_by_xpath("//span[@class='gry']")
values2 = values = [x.text for x in values_elementticker]
print(values2[0])
values_element = browser.find_elements_by_xpath("//div[@id='data_i97']")
values = [x.text for x in values_element]
print("Cash Flows:")
print(values[0])
with open("results.xls", "a") as f:
for i in range(len(values2)):
f.write(values2[0] + "\n")
for i in range(len(values)):
f.write(values[0] + "\n")
browser.close()
restart = input("Do you wish to start again?").lower()
if restart == "yes":
main()
else:
exit()
main()
It currently prints like this 目前它像这样打印
IBM
13,345
12,685
12,857
12,808
12,951
12,741
ABB
2,547
2,819
2,942
3,012
2,850
1,923
I would like it to print like this in excel 我希望它在excel中这样打印
IBM | ABB
13,345 | 2,547
12,685 | 2,819
12,857 | 2,942
12,808 | 3,012
12,951 | 2,850
12,741 | 1,923
I'm not sure if this works in your given context, but reading and writing to a .csv file is much easier and faster. 我不确定这是否可以在您给定的上下文中起作用,但是读写.csv文件更加容易和快捷。 .xls files are designed to be opened with Excel (or similar) and contain formats, sheets and other multi-dimensional data that makes them rather complex to work with.
.xls文件旨在用Excel(或类似格式)打开,并且包含格式,图纸和其他多维数据,这使得它们使用起来相当复杂。
Since a .csv defines columns with commas, they are often easy and quick to read and write. 由于.csv使用逗号分隔列,因此它们通常易于读取和写入。 And at the end of the day, you can still open a .csv with spreadsheet software so it can still be a functional solution.
最终,您仍然可以使用电子表格软件打开.csv,因此它仍然可以作为功能解决方案。
My suggestion: 我的建议:
with open("results.csv", "a") as f:
for x,y in zip(values2,values1):
line = "%s,%s\n" % (x,y)
f.write(line)
If you really insist on writing to an xls file, then it's probably best to go with a module specifically for that purpose, as suggested in Kamal's comment. 如果您真的坚持要写入xls文件,那么最好是为此目的专门使用一个模块,如Kamal的评论中所建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.