ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – 如何找到find_element_by_link_text:NoSuchElement异常?

2019-10-08 14:56:36  阅读:290  来源: 互联网

标签:python css-selectors selenium-webdriver xpath webautomation


这个问题一再被问到 – 尽管尝试了所有的黑客攻击,我仍然无法弄清楚什么是错的.

我尝试将implicitly_wait增加到30(甚至将它增加到100) – 但它没有用.

用例 – :我正在尝试创建一个列表,它将填充页面here中的所有项目,作为基本案例 – 我打算将其绑定到一个迷你模块,我已经拥有scrapy,其中包含所有项目类似的网页元素)抓取链接 – 所以基本上将构建整个管道,发布我完成了这个.

###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)

问题&评论:

>如果您正在回答这个问题 – 请提及为什么这个特定的“find_element_by_link_text”不起作用.
>(非常基础)在我的selenium IDE的GUI中 – >显示所有可用命令 – 为什么我没有看到所有Web元素的css(find_element_by_css_selector) – 是否有办法强制将元素作为CSS选择器读取?
>如果你建议使用其他定位器 – 请提及是否一致的方法来获取元素,给定(1)
>断言是否能够捕获异常并“继续” – 因为即使在尝试“验证”,“断言”循环之后,我仍然无法获取此“find_element_by_link_text”
>我尝试使用Xpath来构建这个“元素”,但是在视图Xpath(在firefox中) – 我什么都没看到,想知道为什么会发生这种情况(当然我删除了命名空间“:x”)

除了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.

相关问题:

> How to use find_element_by_link_text() properly to not raise NoSuchElementException?
> NoSuchElement Exception using find_element_by_link_text when implicitly_wait doesn’t work?

解决方法:

在此之前,我发现find_element_by_link_text方法有时会起作用,有时也不起作用;即使是在一个案例中.我认为这不是访问元素的可靠方式;最好的方法是使用find_element_by_id.

但在您的情况下,当我访问该页面时,没有ID可以帮助您.你仍然可以通过3种方式尝试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’)]”] .

希望能帮助到你.

标签:python,css-selectors,selenium-webdriver,xpath,webautomation
来源: https://codeday.me/bug/20191008/1872644.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有