我正在尝试在 python 中学习 selenium。一切都很好,直到我遇到这样的问题。 IE我有2个元素选择:
天平类型选择要素:
<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')
回答1
实际上,在您的情况下,“平衡类型选择元素”没有“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')
回答2
我通过这样做解决了这个问题:
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,则执行下一个脚本来选择项目。