【问题标题】:Selenium Unable to locate Element (Partial Text Link)Selenium 无法定位元素(部分文本链接)
【发布时间】:2021-12-11 18:04:44
【问题描述】:

我是 Selenium 的新手,我尝试单击第二个页面上的链接(在登录页面之后)。 登录部分正常工作,浏览器转到下一页,但在下一页它引发异常:

这是我的回溯:

Traceback (most recent call last):
  File "d:/Personal_projects/Programmeren/Python/Automate the boring stuff/Chapter12/seleniumTest.py", line 22, in <module>
    weekElem = browser.find_element(By.PARTIAL_LINK_TEXT,'/go/')
  File "C:\Users\****\AppData\Roaming\Python\Python37\site-packages\selenium\webdriver\remote\webdriver.py", line 1246, in find_element
    'value': value})['value']
  File "C:\Users\****\AppData\Roaming\Python\Python37\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "C:\Users\****\AppData\Roaming\Python\Python37\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"partial link text","selector":"/go/"}
  (Session info: chrome=96.0.4664.93)

这是我的代码(登录信息明显模糊):

#! python3

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

import time
browser = webdriver.Chrome()

# First webpage
browser.get('https://www.signupgenius.com/register')
userElem = browser.find_element(By.ID,'email')
userElem.send_keys('************')
passwordElem = browser.find_element(By.ID,'pword')
passwordElem.send_keys('**********')
loginBtnElem = browser.find_element(By.ID,'loginBtnId')
loginBtnElem.click()
time.sleep(10)

# Second  webpage
weekElem = browser.find_element(By.PARTIAL_LINK_TEXT,'/go/')
weekElem.click()

我要查找的元素是:

<a href="/go/10C426245672F85" class="text-orange text-underlined"><strong class="ng-binding">1212</strong></a>

(/go/之后的部分每周都会变化,这就是我使用部分链接文本的原因)

我希望有人能帮我解决这个问题!

编辑我找到了解决方法,通过使用 Xpath 解决了问题:

weekElem = browser.find_element(By.XPATH, '//a[contains(@href,"/go/")]')

如果有人能详细说明为什么部分链接文本不起作用,那会让我更深入地了解 Selenium 的工作原理!

【问题讨论】:

  • Link_text 是您通常看到的 a 标签内的文本。
  • 您提供的 xpath 检查属性 href 与字符串中的任何 /go/ 我建议使用starts-with。否则,您可能会找到匹配 1/go/1 等的 href。

标签: python selenium nosuchelementexception partiallinktext


【解决方案1】:

字符串 go 不是 A 标记的 LINK_TEXT 的一部分。相反,它是 href 属性值的一部分。因此,您不能将 go 用作 PARTIAL_LINK_TEXT


解决方案

您可以使用字符串 go 作为 href 属性值的一部分,如下所示:

  • 使用starts-with()

    weekElem = browser.find_element(By.XPATH, '//a[starts-with(@href,"/go/")]/strong')
    
  • 使用contains()

    weekElem = browser.find_element(By.XPATH, '//a[contains(@href,"/go/")]/strong')
    

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 2022-01-06
  • 2021-06-21
  • 1970-01-01
相关资源
最近更新 更多