python硒-更改Excel Online表中的单元格值

问题描述 投票:2回答:1

是否可以在在线Excel表中使用Selenium for Python编辑单元格的值?

我想模拟用户单击一个单元格并键入它的行为。

我可以读取表中存在的数据,但是不知道如何编辑单元格的内容。读取值可以这样完成:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver=webdriver.Chrome('path_to_driver')
driver.get('my_Online_Excel_sheet')
driver.switch_to.frame('WebApplicationFrame')

# return the text in the cell
driver.find_element_by_xpath('//*[@id="gridRows"]/div[3]/div[3]/div').text

然后我自然尝试了Selenium的send_keys方法,但据我所知,它不适用于这些类型的元素。

我也尝试使用execute_script,它看起来确实很有希望,可以正常运行,但实际上并没有改变单元格中的值。

cell=driver.find_element_by_xpath('//*[@id="gridRows"]/div[3]/div[3]/div')
cell.click()
driver.execute_script("arguments[0].value = 'some_new_value';", cell)

这里是与表中单元格相对应的HTML元素(当前值为101):

<div class="cv-nwr ewr-vab" style="width: 61px; max-heith: 19px; text-align: right;">101</div>
python selenium
1个回答
0
投票

好。我可以使用以下方法更改内部HTML来更改单元格的值:

driver.execute_script("arguments[0].innerHTML = 'new_text';", cell)

遗憾的是,刷新页面后,更改将不成立,但是也许有一种方法可以以编程方式保存工作表,或者通过其他方式保留新值。

© www.soinside.com 2019 - 2024. All rights reserved.