如何find_element_by_link_text有:NoSuchElement异常? [英] How to find_element_by_link_text while having: NoSuchElement Exception?
问题描述
这个问题一再被问过 - 尽管尝试了所有的黑客,我仍然看不出什么问题。
我试图将implicitly_wait增加到30(甚至将其增加到100) - 但它不工作。
case - :我正在尝试创建一个列表,将填充页面中的所有项目这里,作为一个基础案例 - 我打算绑定到一个小模块,我已经与scrapy有所有(页面具有类似的Web元素)爬网链接 - 因此本质上将
###我的源代码 - 通过Selenium IDE生成,导出到一个Python webdriver并操作一点后###
从selenium import webdriver
从selenium.webdriver.common.by导入由
从selenium.webdriver.support.ui import从selenium.common.exceptions中选择
import NoSuchElementException
from selenium.webdriver.support.wait import WebDriverWait
import unittest,time,re
class Einstein .testCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url =http: //shopap.lenovo.com/in/en/laptops/
self.verificationErrors = []
self.accept_next_alert = True
def test_einstein(self):
driver = self.driver
driver.get(self.base_url)
print driver.title
driver.find_element_by_link_text(T430)。click()
打印驱动程序。 title
#driver.find_element_by_xpath(id('facetedBrowseWrapper')/ div / div / div [1] / div [2] / ul [1] / li [1] / a)。 b $ b driver.find_element_by_xpath(// div [@ id ='subseries'] / div [2] / div / p [3] / a。)click()
print driver.title
#driver.find_element_by_xpath(// div [@ id ='subseries'] / div [2] / div / p [3] / a)click()
try:self.assertEqual边缘E530(黑色),driver.find_element_by_link_text(Thinkpad Edge E530(黑色)))文本)
除了AssertionError as e:self.verificationErrors.append(str(e))
#到这里
#**这里的代码失败**#
laptop1 = driver.find_element_by_link_text(Thinkpad Edge E530(Black))。text
print laptop1
price1 = driver.find_element_by_css_selector .price)。text
print price1
detail1 = self.is_element_present(By.CSS_SELECTOR,div.desc.std)
print detail1
def is_element_present (self,how,what):
try:self.driver.find_element(by = how,value = what)
除了NoSuchElementException,e:return False
return True
b $ b def is_alert_present(self):
try:self.driver.switch_to_alert()
除了NoAlertPresentException,e:return False
return True
def close_alert_and_get_its_text self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally:self.accept_next_alert = True
def tearDown(self):
self .driver.quit()
self.assertEqual([],self.verificationErrors)
如果__name__ ==__main__:
unittest.main()
错误&输出:
ekta @ ekta-VirtualBox:〜$ python einstein.py
笔记本电脑&超极本|联想(IN)
ThinkPad T430笔记本电脑商业计算|联想(IN)
购买Lenovo ThinkPad笔记本电脑|联想ThinkPad笔记本电脑价格印度
E
================================== ==============================
错误:test_einstein(__main __。爱因斯坦)
-------------------------------------------------- --------------------
Traceback(最近一次调用):
文件einstein.py,第27行,在test_einstein
try:self.assertEqual(Thinkpad Edge E530(Black),driver.find_element_by_link_text(Thinkpad Edge E530(Black))。文本)
文件/usr/local/lib/python2.7/ dist-packages / selenium / webdriver / remote / webdriver.py,行246,在find_element_by_link_text
中返回self.find_element(by = By.LINK_TEXT,value = link_text)
文件/ usr / local / lib / python2.7 / dist-packages / selenium / webdriver / remote / webdriver.py,行680,在find_element
{'using':by,'value':value})['value']
文件/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py,第165行,在执行
self.error_handler.check_response(response)
文件/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py,第158行,在check_response
中raise exception_class(message,screen,stacktrace)
NoSuchElementException:Message:u'Unable to locate element:{method:link text,selector:Thinkpad Edge E530(Black)} Stacktrace:
在FirefoxDriver.prototype.findElementInternal_(file:///tmp/tmphli5Jg/extensions/fxdriver@googlecode.com/components/driver_component.js:8444)
at fxdriver.Timer.prototype.setTimeout /<.notify(file:///tmp/tmphli5Jg/extensions/fxdriver@googlecode.com/components/driver_component.js:386)
----------- -------------------------------------------------- ---------
在79.348s中执行1个测试
FAILED(errors = 1)
问题&
如果您回答这个问题,请说明为什么这个特定的find_element_by_link_text无法使用。(非常基本)在我的selenium IDE的GUI - >显示所有可用的命令 - 为什么我看不到css(find_element_by_css_selector) - 是否有一种方法可强制将元素读取为CSS选择器?
请提供是否会以一致的方式抓取元素(1)
请确认工作以捕获异常并移动即使在尝试验证,断言循环后,我仍然无法获取这个find_element_by_link_text
其他我尝试除了 implicity_wait(30)
:
find_element_by_partial_link(Thinkpad)并附加Unicode到这里(不确定是否正在阅读括号(,driver.find_element_by_link_text(uThinkpad Edge E530(黑色) 。
相关问题:
- 如何使用find_element_by_link_text()正确地不引发NoSuchElementException?
- Selenium - find_element_by_link_text - NoSuchElementException
在我之前, find_element_by_link_text
方法有时工作,有时不工作;即使在单个案例中。我认为这不是一个可靠的方式来访问元素;最好的方法是使用 find_element_by_id
。
但是在你的情况下,当我访问该页面时,没有id可以帮助你。仍然可以通过三种方式尝试 find_elements_by_xpath
:
1-访问标题: find_element_by_xpath [ // a [contains(@title ='T430')]]
2-访问文本: find_element_by_xpath [// a [contains(text(),'T430')]]
3-访问href: find_element_by_xpath [// a [contains(@href ='http://www.thedostore.com/laptops/thinkpad-laptops/thinkpad-t430-u-black-627326q.html')]\"]
。
希望它有帮助。
This question has been asked over and over again - and in-spite of trying all the hacks I still can't seem to figure out what's wrong.
I tried increasing the implicitly_wait to 30 (and even increased it upto 100) - yet it did not work.
Use case -: I am trying to create a list that wil populate all the items in the page here, as a base case - and I intend to bind this to a mini-module that I already have with scrapy which has all (pages with similar web elements) crawled links - so essentially will be building the whole pipeline, post I am done with this.
###My source code - generated via Selenium IDE, exported to a Python webdriver and manipulated a little later ###
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.wait import WebDriverWait
import unittest, time, re
class Einstein(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "http://shopap.lenovo.com/in/en/laptops/"
self.verificationErrors = []
self.accept_next_alert = True
def test_einstein(self):
driver = self.driver
driver.get(self.base_url)
print driver.title
driver.find_element_by_link_text("T430").click()
print driver.title
# driver.find_element_by_xpath("id('facetedBrowseWrapper')/div/div/div[1]/div[2]/ul[1]/li[1]/a").click()
driver.find_element_by_xpath("//div[@id='subseries']/div[2]/div/p[3]/a").click()
print driver.title
# driver.find_element_by_xpath("//div[@id='subseries']/div[2]/div/p[3]/a").click()
try: self.assertEqual("Thinkpad Edge E530 (Black)", driver.find_element_by_link_text("Thinkpad Edge E530 (Black)").text)
except AssertionError as e: self.verificationErrors.append(str(e))
# Everything ok till here
#**THE CODE FAILS HERE**#
laptop1 = driver.find_element_by_link_text("Thinkpad Edge E530 (Black)").text
print laptop1
price1 = driver.find_element_by_css_selector("span.price").text
print price1
detail1 = self.is_element_present(By.CSS_SELECTOR, "div.desc.std")
print detail1
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException, e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException, e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
Errors & output :
ekta@ekta-VirtualBox:~$ python einstein.py
Laptops & Ultrabooks | Lenovo (IN)
ThinkPad T430 Laptop PC for Business Computing | Lenovo (IN)
Buy Lenovo Thinkpad Laptops | Lenovo Thinkpad Laptops Price India
E
======================================================================
ERROR: test_einstein (__main__.Einstein)
----------------------------------------------------------------------
Traceback (most recent call last):
File "einstein.py", line 27, in test_einstein
try: self.assertEqual("Thinkpad Edge E530 (Black)", driver.find_element_by_link_text("Thinkpad Edge E530 (Black)").text)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 246, in find_element_by_link_text
return self.find_element(by=By.LINK_TEXT, value=link_text)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 680, in find_element
{'using': by, 'value': value})['value']
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 165, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 158, in check_response
raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: u'Unable to locate element: {"method":"link text","selector":"Thinkpad Edge E530 (Black)"}' ; Stacktrace:
at FirefoxDriver.prototype.findElementInternal_ (file:///tmp/tmphli5Jg/extensions/fxdriver@googlecode.com/components/driver_component.js:8444)
at fxdriver.Timer.prototype.setTimeout/<.notify (file:///tmp/tmphli5Jg/extensions/fxdriver@googlecode.com/components/driver_component.js:386)
----------------------------------------------------------------------
Ran 1 test in 79.348s
FAILED (errors=1)
Questions & comments:
If you are answering this question - please mention why this specific "find_element_by_link_text" does not work.
(Very Basic) In the GUI of my selenium IDE -> Show all available commands - why dont I see the css (find_element_by_css_selector) for all the web elements - is there a way to force feed an element to be read as a CSS selector ?
In case you suggest using some other locator - please mention if that will be consistent way to fetch elements, given (1)
Does assert work to capture the exceptions and "move on" - since even after trying "verify" , "assert" loops, I still cant fetch this "find_element_by_link_text"
I tried using Xpath to build this "element" , but in the view Xpath (in firefox) - I see nothing, to clue why that happens (Of course I removed the namespace ":x" )
Other things I tried apart from implicity_wait(30)
:
find_element_by_partial_link("Thinkpad") and appending Unicode to this (wasn’t sure if it was reading the brackets ( , driver.find_element_by_link_text(u"Thinkpad Edge E530 (Black)").text, still did not work.
Related questions:
- How to use find_element_by_link_text() properly to not raise NoSuchElementException?
- Selenium - find_element_by_link_text - NoSuchElementException
It happened to me before that the find_element_by_link_text
method sometimes works and sometimes doesn't work; even in a single case. I think it's not a reliable way to access elements; the best way is to use find_element_by_id
.
But in your case, as I visit the page, there is no id to help you. Still you can try find_elements_by_xpath
in 3 ways:
1- Accessing title: find_element_by_xpath["//a[contains(@title = 'T430')]"]
2- Accessing text: find_element_by_xpath["//a[contains(text(), 'T430')]"]
3- Accessing href: find_element_by_xpath["//a[contains(@href = 'http://www.thedostore.com/laptops/thinkpad-laptops/thinkpad-t430-u-black-627326q.html')]"]
.
Hope it helps.
这篇关于如何find_element_by_link_text有:NoSuchElement异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!