python - 无法单击 iframe 中的下拉菜单 - Selenium Python

标签 python selenium

问题:尝试使用 Chrome 驱动程序和 Selenium 以及 Python 单击 iframe 内的下拉菜单。

大家好。昨天一位用户好心地帮助我解决了一个新手查询。我无法单击 url 中的链接,这是因为我必须切换到 iframe。这部分代码现在可以运行,我导航到一个下拉菜单,我希望对其进行选择。

我尝试通过修改代码来访问此元素,但收到无法找到该元素的回溯。我正在尝试使用 Select 将下拉列表的值更改为“Aldershot”,按名称和可见文本查找元素。任何建议都非常感激。

#setup
from selenium import webdriver
from selenium.webdriver.support.select import Select

#utilise chrome driver to open specified webpage
driver = webdriver.Chrome("/Users/philthomas/Desktop/web/chromedriver")
driver.maximize_window()
driver.get("http:enfa.co.uk")

#switch to specific iframe and click on 'clubs' button on left hand menu
driver.switch_to.frame(2);
ClubsLink=WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,
"//span[contains(text(),'Clubs')]")))
ClubsLink.click()

#find drop-down menu and choose 'Aldershot'
select_box = Select(driver.find_element_by_name("team"))
select_box.select_by_visible_text("Aldershot")

回溯:

Traceback

HTML:

HTML from url

最佳答案

您收到错误的原因是 iframe 内存在选择下拉列表。 您需要先切换到 iframe 才能选择元素。

引发WebDriverWaitframe_to_be_available_and_switch_to_it()

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.support.select import Select

#utilise chrome driver to open specified webpage
driver = webdriver.Chrome("/Users/philthomas/Desktop/web/chromedriver")

driver.maximize_window()
driver.get("http:enfa.co.uk")

#switch to specific iframe and click on 'clubs' button on left hand menu
WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,"left")))
ClubsLink=WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,
"//span[contains(text(),'Clubs')]")))
ClubsLink.click()

#return from iframe
driver.switch_to.default_content()
#Switch to another iframe
WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME,"main")))

#find drop-down menu and choose 'Aldershot'
teamselect=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.NAME,"team")))
select_box = Select(teamselect)
select_box.select_by_visible_text("Aldershot")

浏览器快照:

enter image description here

关于python - 无法单击 iframe 中的下拉菜单 - Selenium Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59108289/

相关文章:

python - ModelChoiceField 的 Django 表单查询集

python - Pandas:如何删除 Pandas 数据框中所有列的前导缺失值?

selenium - 与桌面屏幕分辨率交互的 Windows 服务

java - 在 selenium webdriver 中执行 javascript 时发生错误

java - 如何跳过执行期间挂起/卡住的测试 Selenium - Maven - Jenkins

java - 将 WebElement 转换为 int

Python:不排除 map (字典)之后的行

python - 在 MacOSX10.6 上运行 python 服务器时出现 MySQLdb 错误

python - 使用 python 将值导入 MySQL 数据库时出现 SQL 语法错误

python - 如何使用 Factory_Boy 创建管理员用户?