Selenium 不会加载链接文本 - 我错过了什么

尝试让 Selenium 在访问注册表单之前单击 cookie 策略按钮上的“接受”。(我想自动化等候名单功能,因为这在这个健身房总是一场竞赛)但我陷入了第一个障碍,并花了几个小时试图破译错误消息。你能帮忙吗?


代码


import selenium

from selenium import webdriver

from selenium.webdriver.common.keys import Keys


PATH = "C:\Program Files (x86)\chromedriver.exe"

driver = webdriver.Chrome(PATH)


driver.get("https://member.superfit.club/")


driver.find_element_by_link_text("Akzeptieren").click()

错误信息:


Traceback (most recent call last):

  File "C:\Users\Csongor\Dropbox\Coding\new test 6th oct 2020\test.py", line 8, in <module>

    driver.get("https://member.superfit.club/").find_element_by_link_text("Akzeptieren").click()

AttributeError: 'NoneType' object has no attribute 'find_element_by_link_text'


浮云间
浏览 114回答 4
4回答

慕勒3428872

您可以通过文本值找到该按钮。试试这个代码:import seleniumfrom selenium import webdriverfrom selenium.webdriver.common.keys import KeysPATH = "C:\Program Files (x86)\chromedriver.exe"driver = webdriver.Chrome(PATH)driver.get("https://member.superfit.club/")#driver.find_element_by_link_text("Akzeptieren").click()driver.find_element_by_xpath('//button[contains(text(), "Akzeptieren")]').click()

尚方宝剑之说

你为什么不直接使用xpath而不是link text?driver.find_element_by_xpath('//*[@id="CookieModelButtom"]/div/div/div/div/button[1]').click()这工作得很好。我建议您使用xpathsorCSS Selectors代替Link Texts。

慕尼黑的夜晚无繁华

您显示的代码不反映错误堆栈跟踪中的内容。显然,你是find_element_by_link_text这样调用的:driver.get("https://member.superfit.club/").find_element_by_link_text("Akzeptieren").click()当你应该像你自己展示的那样做时:driver.get("https://member.superfit.club/")driver.find_element_by_link_text("Akzeptieren").click()

当年话下

find_element_by_link_text() 适用于锚元素而不是按钮元素。您与之交互的元素是按钮,因此您可以识别 ID、NAME、XPATH 或 CSS 选择器。我建议你使用WebDriverWait()and element_to_be_clickable() 和下面的 css 选择器。WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"button.btn.btn-success"))).click()您需要导入以下库。from selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as EC
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python