簡體   English   中英

Python Selenium 導出數據 csv

[英]Python Selenium Export data in csv

我正在嘗試使用 Selenium 導出 web 抓取的結果,但它只導出我列表的第一個數據,我需要它來導出所有數據。

在 csv 我希望它出來:


| 標題 | 出售者 | 銷售_Perc | 時間_左 |

| 標題1 | 亞馬遜 | 10% 公寓 | 06:05:12 |

| 標題2 | 亞馬遜 | 18% 公寓 | 08:55:11 |

from selenium import webdriver
from lxml import html
from time import sleep

driver = webdriver.Chrome('c:/bin/chromedriver')

lst=[]
for page_nb in range(1, 2):
    driver.get('https://www.amazon.com.mx/gp/goldbox/ref=gbps_ftr_s-5_2c3b_page_' + str(page_nb) + '?gb_f_c2xvdC01=dealStates:AVAILABLE%252CWAITLIST%252CWAITLISTFULL%252CEXPIRED%252CSOLDOUT,dealTypes:LIGHTNING_DEAL,page:' + str(page_nb) + ',sortOrder:BY_SCORE,dealsPerPage:48&pf_rd_p=d8b66f14-9e78-4a85-b04f-327a0b562c3b&pf_rd_s=slot-5&pf_rd_t=701&pf_rd_i=gb_main&pf_rd_m=AVDBXBAVVSXLQ&pf_rd_r=5YBFC04YTSW7FDETY9RQ&ie=UTF8')
    sleep(2)
    for product_tree in driver.find_elements_by_xpath('//div[contains(@id, "101_dealView_")]'):
        title = product_tree.find_element_by_xpath('.//a[@id="dealTitle"]/span').text
        vendido = product_tree.find_element_by_xpath('.//span[@id="shipSoldInfo"]').text
        apartado = product_tree.find_element_by_xpath('.//span[@class="a-size-mini a-color-secondary inlineBlock unitLineHeight"]').text
        tventa = product_tree.find_element_by_xpath('.//span[@role="timer"]').text
        lst.append([title, vendido, apartado, tventa])
        #print(title, vendido, apartado, tventa)

driver.close()

#exporting data into a csv file
import csv
header = ['Titulo', 'Sold_by', 'Sold_Perc', 'Time_left']
data = [title, vendido, apartado, tventa]

with open('Test.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(header)
    writer.writerow(data)
    

print('Done...')

我認為您將錯誤的清單放入您的作家中。 您將所有抓取變量保存在lst中,因此請記住在您的 csv 中寫入lst

import csv
header = ['Titulo', 'Sold_by', 'Sold_Perc', 'Time_left']

with open('Test.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(header)
    // replace data with lst
    writer.writerow(lst)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM