Skip to main content
 首页 » 编程设计

python之如何在具有 : NoSuchElement Exception 的情况下通过链接文本查找元素

2024年11月01日14lexus

这个问题已经被一遍又一遍地问了——尽管尝试了所有的技巧,但我似乎仍然无法弄清楚问题出在哪里。

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

用例 -:我正在尝试创建一个列表来填充页面中的所有项目 here ,作为一个基本案例 - 我打算将它绑定(bind)到我已经使用 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) 

问题和评论:

  1. 如果您要回答这个问题 - 请说明为什么这个特定的“find_element_by_link_text”不起作用。

  2. (非常基本)在我的 selenium IDE 的 GUI 中 -> 显示所有可用命令 - 为什么我看不到所有 Web 元素的 css (find_element_by_css_selector) - 有没有办法强制输入一个要作为 CSS 选择器读取的元素?

  3. 如果您建议使用其他定位器 - 请说明在给定 (1) 的情况下,这是否是获取元素的一致方式

  4. 断言是否可以捕获异常并“继续”——因为即使在尝试“验证”、“断言”循环之后,我仍然无法获取此“find_element_by_link_text”

  5. 我尝试使用 Xpath 构建此“元素”,但在 Xpath View (在 firefox 中)中 - 我什么也没看到,以了解为什么会发生这种情况(当然我删除了 namespace “: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. 

相关问题:

请您参考如下方法:

我之前遇到过,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')]"].

希望对您有所帮助。