使用Selenium Python时出现NoSuchElementException
我在用Selenium在Python中查找元素时,总是遇到NoSuchElementException这个错误。我在等页面完全加载,而且我也切换到了正确的框架(至少我觉得是这样!)。
这是我的代码:
driver.get("https://www.arcgis.com/home/signin.html")
driver.implicitly_wait(10)
driver.switch_to_frame("oAuthFrame")
elem = driver.find_element_by_name('username')
elem1 = driver.find_element_by_name('password')
这是我想访问的网页部分:
<input id="user_username" class="textBox" type="text" name="username" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
它位于
<iframe dojoattachpoint="_iFrame" id="oAuthFrame" scrolling="no" style="display: block; border: 0px;" marginheight="0" marginwidth="0" frameborder="0" width="400" height="500"...>
你可以自己去查看源代码,链接是 https://www.arcgis.com/home/signin.html
完整的错误输出:
Traceback (most recent call last):
File "C:\Python34\beginSample.py", line 12, in <module>
elem = driver.find_element_by_name('username')
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 302, in find_element_by_name
return self.find_element(by=By.NAME, value=name)
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 662, in find_element
{'using': by, 'value': value})['value']
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 173, in execute
self.error_handler.check_response(response)
File "C:\Python34\lib\site-packages\selenium\webdriver\remote\errorhandler.py"
, line 164, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: 'no such element\n
(Session info: chrome=35.0.1916.153)\n (Driver info: chromedriver=2.9.248315,pl
atform=Windows NT 6.1 SP1 x86_64)'
如果有人能帮我找出问题所在,我会非常感激。
更新:我现在在使用动作,并且我调试到没有错误的地步,但它也没有输入任何内容。这是我的代码:
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
actions.send_keys("sd")
actions.send_keys(Keys.TAB)
actions.send_keys("bg")
actions.perform()
1 个回答
我个人比较喜欢使用xpath,并利用xquery的功能。你仍然可以使用其他的附加选项,因为它们通常是元素的“属性”,但这样做能让你在处理复杂类型时更灵活。我可以通过下面这两个附加的xpath找到用户名和密码的输入框。你不需要先切换到iframe……虽然有些直接调用,比如名字,似乎不太管用……但xpath的方式对我有效。
element = driver.find_element_by_xpath("//input[@name='username']")
element1 = driver.find_element_by_xpath("//input[@name='password']")
更新: 我能重现这个问题……我不太确定为什么这些定位器在这个特定情况下不工作,但这里有一个有效的解决办法。页面加载时,焦点默认会放在用户名框上。
actions = selenium.webdriver.common.action_chains.ActionChains(driver)
actions.SendKeys("sd").Perform()
actions.SendKeys(selenium.webdriver.common.Keys.Tab).Perform()
actions.SendKeys("bg").Perform()
http://selenium.googlecode.com/git/docs/api/py/webdriver/selenium.webdriver.common.action_chains.html 如果我能找到直接连接到这些输入框的方法,我会再更新。
更新:在Chrome浏览器中,如果你抓取特定的iFrame,你会看到一个错误,提示你的浏览器不支持这个iFrame。我认为问题可能出在浏览器无法正确读取它……尽管它似乎能正确渲染并允许功能使用。由于Selenium是基于DOM选择的,它会尝试使用类似的方式来找到这个元素。我建议你试试 driver.execute_script("这里放脚本")
,看看能否仅用javascript找到它。如果可以的话,你就得继续使用javascript,直接修改控件的属性,然后执行一个javascript提交事件来点击按钮。