我正在尝试学习python中的硒。一切都很好,直到我遇到这样的问题。也就是说,我有两个元素选择:
平衡类型选择元素:
<select class="form-control " id="balance_type_id" name="balance_type_id">
<option selected="" disabled="">-- Pilih --</option>
<option value="1, Deposit">Deposit</option>
<option value="3, Pengembalian Dana">Pengembalian Dana</option>
<option value="4, Sharing Profit Proyek">Sharing Profit Proyek</option>
</select>
项目选择元素:
<select id="project_option_selection" class="form-control " name="project_id"></select>
如果我选择Pengembalian Dana选项,项目选择元素将显示选项元素:
<select id="project_option_selection" class="form-control " name="project_id">
<option selected="" disabled="">-- Pilih --</option>
<option value="1">Project 1</option>
<option value="2">Project 2"</option>
</select>
当代码要对该元素执行操作时,它总是抛出错误。我试过使用显式等待。但我穿它的方式有问题吗?是否有任何解决方案,让我能够选择对项目选择行动。我尝试使用预期条件text_to_be_present_in_value
driver.get("http://127.0.0.1:8000/cash-mutations/create/incoming-balance")
balance_type_selection = driver.find_element(by=By.NAME, value="balance_type_id")
Select(balance_type_selection).select_by_visible_text("Pengembalian Dana")
try:
wait.until(EC.text_to_be_present_in_value((By.NAME, 'balance_type_id', "3")))
print("Pendanaan Proyek is selected")
# Select(driver.find_element(by=By.NAME, value="project_id")).select_by_value("1")
except:
print('gagal')
其实没有" value ";平衡类型选择元素"在您的情况下,它们只是<select>
标签下的选项。
所以wait.until(EC.text_to_be_present_in_value((By.NAME, 'balance_type_id', "3")))
不会有任何反应
在你的代码中试试:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait
driver.get("http://127.0.0.1:8000/cash-mutations/create/incoming-balance")
balance_type_selection = driver.find_element(by=By.NAME, value="balance_type_id")
Select(balance_type_selection).select_by_visible_text("Pengembalian Dana")
try:
wait(driver, timeout=10).until(EC.presence_of_element_located(
(By.XPATH, '//*[@id="project_option_selection"]/option[1]')))
print("Pendanaan Proyek is selected")
# Select(driver.find_element(by=By.NAME, value="project_id")).select_by_value("1")
except:
print('gagal')
我已经解决了这个问题:
try:
wait.until(EC.text_to_be_present_in_element((By.XPATH, '//*[@id="balance_type_id"]/option[3]'), 'Pengembalian Dana'))
Select(driver.find_element(by=By.NAME, value="project_id")).select_by_value("1")
except:
print('gagal')
所以我做的第一件事是通过使用text_to_be_present_in_element
选择Pendanaan Proyek的选项标签。因此,我通过XPATH为Pendanaan Proyek选择了选项。如果选择了Pendanaan Proyek,那么执行下一个脚本来选择项目。