您的位置:首页 > 其它

定位不到元素的一般解决方法

2017-01-01 01:22 225 查看

内联框架标签frame/iframe

这个是常一个页面见的原因,frame和iframe相当于在页面在镶嵌了一个新的页面,webdriver每次只能在一个页面上操作,网页中出现这两个标签时要使用switch_to.frame()方法切换到frame/iframe中再进行其他操作。

使用firebug插件打开时先查看如图框框内:



像这里框架是iframe,要先切换到iframe再进行其他操作。

实例:

from selenium import webdriver
from time import sleep
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Firefox()
driver.get(r"http://www.126.com")
driver.set_window_size(500,400)
driver.switch_to.frame("x-URS-iframe")  #先切换到iframe
driver.implicitly_wait(10)
try:
e1=driver.find_element_by_xpath("//*[@id='account-box']/div[2]/input[1]")
e2=driver.find_element_by_xpath("//*[@name='password']")
e3=driver.find_element_by_xpath(".//*[@id='dologin']")
except NoSuchElementException as e:
print(e)
else:
e1.clear()
e1.send_keys("lxxx")
e2.clear()
e2.send_keys("yuxxxe1xxx..")
e3.click()
如果是Top Window就可以直接操作:



switch_to.fram()方法默认以iframe的id或name定位,如果该框架没有id或name,可以通过其他的定位方式找到该框架再切换到该框架:

el = driver.find_element_by_xpath("//*[@id='apsd']/div[2]/div/iframe")
driver.switch_to.frame(el)
...
在该内联框架完成相关操作后同以下方法跳出该iframe:

switch_to.parent_frame()      跳出该框架

switch_to.default_content()  跳到最外层页面


打开多了个窗口

在页面操作过程中有时点击某个链接打开了新的窗口,如果直接在新的窗口中直接操作也会报错。

这时需要使用switch_to_window()切换到新的窗口再进行操作。

实例:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from time import *

driver = webdriver.Firefox()
driver.get(r"http://www.runoob.com") #r原始字符串,防止反斜杠转义
driver.set_window_size(1500,800)
sleep(1)
shouye_handle =driver.current_window_handle
try:
driver.implicitly_wait(5)
driver.find_element_by_link_text("菜鸟笔记").click()
all_handles =driver.window_handles
for i in all_handles:
if i != shouye_handle:
driver.switch_to_window(i)   #切换到新的窗口再进行其他操作。
e2=driver.find_element_by_link_text("互联网")
#e1="window.scrollTO(0,500);"

except NoSuchElementException as e:
print(e)
else:
#driver.execute_script(e1)
e2.click()
finally:
driver.quit()


xpath描述错误

网页层级复杂,用xpath定位元素也容易出错,一要注意xpath的写法;二换个属性再试试定位

参考这篇文章:

http://blog.csdn.net/jojoy_tester/article/details/53453888

页面元素还完整加载

解决方法有3个:

time 模块中有个sleep(),在定位元素前可以先休眠以下,slee(1);
设置元素显性等待;
设置元素隐性等待;

动态id和元素属性不唯一

动态id是标签指每次加载页面该id都会变化,如那些id="login2647788",以数学结尾的id不能用于定位;
定位的元素属性其他标签也用,如class名、tag名,不能用于定位;

元素定位的顺序问题

有些元是操作操作前一个元素后,才出现的,所有要看清楚。

不可见元素问题

。。。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: