簡體   English   中英

Python selenium 數據傳輸到 excel - 最優解

[英]Python selenium data transfer to excel - optimal solution

我使用下面的代碼將抓取的數據傳輸到 excel 表。 它有效,但缺點是執行時間。 以這種方式傳輸大約 200 行 x 2 列(400 個元素)大約需要 5-10 秒。 我希望有人可以用一些更有效的解決方案提示我。

Python代碼:

driver=webdriver.Chrome(executable_path=r'C:/chromedriver.exe')     
driver.get('https://www...table')    
First = driver.find_elements_by_xpath('//table[@id="cr1"]/tbody/tr/td[1]')
Second = driver.find_elements_by_xpath('//table[@id="cr1"]/tbody/tr/td[2]')
xlapp = win32.Dispatch('Excel.Application')
wbook = xlapp.Workbooks.Open(r'Test.xlsm')
sheet = wbook.Worksheets('COMM')
for i in range(len(First)):
    sheet.Cells(i,1).Value = First[i]
    sheet.Cells(i,2).Value = Second[i] 

一種有效的方法是從表中抓取數據並使用DataFramepandas將數據寫入CSV/XLS/XLSX 文件中,如下所示:

driver=webdriver.Chrome(executable_path=r'C:/chromedriver.exe')     
driver.get('https://www...table')    
First = [my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, '//table[@id="cr1"]/tbody/tr/td[1]')))]
Second = [my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, '//table[@id="cr1"]/tbody/tr/td[2]')))]
df = pd.DataFrame(data=list(zip(First, Second)), columns=['First', 'Second'])
print(df)
df.to_excel(r'C:\Data_Files\output_files\Test.xlsx', index=False)
driver.quit()

暫無
暫無

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

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