【问题标题】:Python Selenium find_element_by_link_text not working for mePython Selenium find_element_by_link_text 不适合我
【发布时间】:2021-10-16 23:55:33
【问题描述】:

我试图让 Selenium 将我登录到 Soundcloud,但 find_element_by_link_text 属性对我不起作用,但它似乎适用于“了解更多”和“上传您自己的”。为什么它对网页上的某些元素有效,而对其他元素无效??

from tkinter import *
import random
import urllib.request
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import requests
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options



driver = webdriver.Chrome(executable_path='/Users/quanahbennett/PycharmProjects/SeleniumTest/chromedriver')
url= "https://soundcloud.com/"
driver.get(url)
#time.sleep(30)

wait = WebDriverWait(driver, 10)
link = driver.find_element_by_link_text('Sign in');
link.click()


breakpoint()

【问题讨论】:

  • 有几个原因。元素可能在 iframe 中,元素可能实际上不在页面中,等等。

标签: python html selenium


【解决方案1】:

您尝试查找的元素Sign in 不在a 标记中以使用driver.find_element_by_link_text。它在button 标记中。

尝试如下并确认:

driver.get("https://soundcloud.com/")
wait = WebDriverWait(driver,30)

# Cookie pop-up
wait.until(EC.element_to_be_clickable((By.ID,"onetrust-accept-btn-handler"))).click()

# Click on Sign-in
wait.until(EC.element_to_be_clickable((By.XPATH,"//div[@class='frontHero__signin']//button[@title='Sign in']"))).click()

【讨论】:

  • 我使用这些代码行并收到错误 selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable at point
  • 实际上我很抱歉,一旦我删除了 cookie 弹出窗口的代码行,它就可以完美运行,谢谢!请问您是如何检索元素的 XPath 的?我不知道该怎么做
  • @drakepolo - 您现在可以参考这些链接 - LInk1, Link2
【解决方案2】:

德雷克波罗,

find_element_by_link_text()

该功能仅适用于包含在锚标记中的文本(有时称为标记)。

下面是outerHTML 对应Upload your own

<a href="/upload" class="frontContent__uploadButton sc-button sc-button-cta sc-button-primary sc-button-large">Upload your own</a>

请参见此处,文本 Upload your own 包含在 HTML 中的标记中。

但是对于Sign In 按钮:

<button type="button" class="g-opacity-transition frontHero__loginButton g-button-transparent-inverted sc-button sc-button-medium loginButton" tabindex="0" title="Sign in" aria-label="Sign in">Sign in</button>

它被包裹在一个按钮标签中。

这就是find_element_by_link_text() 不适用于Sign In 按钮的原因。

你可以像这样切换到css selector

driver.find_element_by_css_selector('button.frontHero__loginButton')

xpath using

driver.find_element_by_xpath("//button[contains(@class,'frontHero__loginButton')]")

请注意,CSS 的优先级高于 xpath

【讨论】:

  • 谢谢!!!请问您是如何知道元素的 XPath 的。我似乎无法理解
  • //tagName[@attributeName='attributeValue'] 这是 XPath 的基本语法。 Selenium 使用 XPath v1.0。有更新的版本,如 v2.0 和 v3.0。 contains 基本上是我用过的 xpath 方法。请在此处阅读更多信息w3schools.com/xml/xpath_axes.asp
  • SO 中的约定是通过单击答案旁边的勾号/复选标记将答案标记为已接受。
猜你喜欢
  • 2012-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-14
  • 2021-12-07
相关资源
最近更新 更多