我尝试在 this 上的表行中输入新值使用 Selenium 的网站。到目前为止我的方法:
URL = "https://sigmazone.com/catapult-grid/"
browser = webdriver.Firefox("/usr/lib/firefox")
browser.get(URL)
# enter number of rows = 1
num_rows = browser.find_element_by_id("noOfRows")
num_rows.clear()
num_rows.send_keys("1")
# updating number of rows
update_btn = browser.find_element_by_id("updateNoOfRows")
update_btn.click()
cells = browser.find_elements_by_class_name("htRight")
# skipping the first entry in cells because it contains a div with the whole table
for cell in cells[1:]:
cell.click()
cell.send_keys("150")
尝试这个给了我 Message: Element <td class="htRight current highlight"> is not reachable by keyboard
来自send_keys(150)
方法。
更新:
我就是这样解决的。重置行动链至关重要。否则,每次执行 action.perform()
时都会执行所有先前的操作
def set_val(selected_cell, value):
action.move_to_element(selected_cell).double_click() # select the cell
action.send_keys(Keys.BACKSPACE, Keys.BACKSPACE, Keys.BACKSPACE) # deleting previous numbers
action.send_keys(str(value)) # send the value
action.perform() # perform the action chain
action.reset_actions() # this alone did not reset the action chain completely
for device in action.w3c_actions.devices:
device.clear_actions()
最佳答案
您必须先让页面完全加载,然后才能访问其中的元素。
请尝试这个:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
URL = "https://sigmazone.com/catapult-grid/"
browser = webdriver.Firefox("/usr/lib/firefox")
wait = WebDriverWait(browser, 20)
browser.get(URL)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "td.htRight")))
cells = browser.find_elements_by_class_name("htRight")
# skipping the first entry in cells because it contains a div with the whole table
for cell in cells[1:]:
cell.click()
cell.send_keys("150")
UPD
如果 cell.send_keys("150")
不起作用,请尝试使用 actions
:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
URL = "https://sigmazone.com/catapult-grid/"
browser = webdriver.Firefox("/usr/lib/firefox")
wait = WebDriverWait(browser, 20)
actions = ActionChains(browser)
browser.get(URL)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "td.htRight")))
cells = browser.find_elements_by_class_name("htRight")
# skipping the first entry in cells because it contains a div with the whole table
for cell in cells[1:]:
cell.click()
actions.send_keys('150').perform()
关于python - 使用 selenium 更改表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69524805/