我正试图从一个网站上取消最佳航班。结果如下所示。.3最佳航班时刻表。有人可以帮助将其写入以下列中的csv:Flightname时间持续时间票价 晚上10:15 –晚上11:50 酷航 4h 5m SIN–MAA 马不停蹄 $ 220 往返 上午5:40 –上午7:35 靛青 4h 25m SIN–MAA 马不停蹄 $ 245 往返 12:10 AM – 1:50 AM 印度航空快车 4h 10m SIN–MAA 马不停蹄 $ 299 往返
我的代码如下: flights = driver.find_element_by_xpath(“ // ol [@jstcache ='8852']”) 打印(flights.text)
答案 0 :(得分:0)
您可以使用csv模块写入提取的数据。
从csv读取示例用法:
import csv
>>> with open('eggs.csv', newline='') as csvfile:
... spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
... for row in spamreader:
... print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
向csv写入示例用法:
import csv
with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
在您的情况下,您可以像这样使用它:
import csv
data = ['3:00 PM – 4:25 PM\nThai AirAsia\n2h 25m\nSIN–DMK\nNonstop\n$136\nround trip\n10:05 PM – 11:30 PM\nScoot\n2h 25m\nSIN–DMK\nNonstop\n$137\nround trip\n7:10 PM – 8:40 PM\nJetstar\n2h 30m\nSIN–BKK\nNonstop\n$149\nround trip'][0].split('\n')
numberOfFlights = 3
for i in range(numberOfFlights+1):
data.insert(7*i+i, '\n')
with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['Time' , 'Flightname' , 'Duration' , 'Fare' , 'Trip'])
spamwriter.writerow(data)