【问题标题】:Click() function not working in python / seleniumClick() 函数在 python / selenium 中不起作用
【发布时间】:2020-10-04 11:16:47
【问题描述】:

如您所见,我开始编写一个机器人来在 SNKRS 上警察运动鞋。我已经编写了一些无用的东西,但我们不在乎。我希望机器人点击登录按钮,但最后当我运行代码时,它会打开 Chrome,然后打开耐克网站,但随后它没有点击按钮,我收到以下错误消息:

Traceback (most recent call last):
  File "C:/Users/xxx/xxx/xxx/xxx/xxx/SNKRS_bot/snkrs bot.py", line 11, in <module>
    loginBtn = driver.find_elements_by_xpath("/html/body/div[2]/div/div/div[1]/div/header/div[1]/section/div/ul/li[1]/button").click()
AttributeError: 'list' object has no attribute 'click'

这是我的代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://www.nike.com/ch/fr/launch?s=upcoming")

time.sleep(3)
loginBtn = driver.find_elements_by_xpath("/html/body/div[2]/div/div/div[1]/div/header/div[1]/section/div/ul/li[1]/button").click()

time.sleep(6)
driver.quit()

非常感谢

【问题讨论】:

  • 我根本找不到您要查找的 xpath。此外,您正在调用find_elements_by_xpath,它返回一个列表。假设它找到一个或多个满足 xpath 的元素,则不能将列表传递给 click 函数;您必须传递列表的元素之一。与其使用对sleep 的调用,不如在一开始就调用driver.implcitly_wait(6)。然后,驱动程序将等待最多 6 秒以找到一个元素,但如果它更快找到该元素,它将更快返回。

标签: python selenium selenium-webdriver


【解决方案1】:

查看我对您发布的问题的评论。最后我确实找到了你的按钮,但如果不使用 JavaScript,它就无法点击:

from selenium import webdriver

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
try:
    driver.implicitly_wait(6) # wait up to 6 seconds to find an element
    driver.get("https://www.nike.com/ch/fr/launch?s=upcoming")
    
    loginBtns = driver.find_elements_by_xpath("/html/body/div[2]/div/div/div[1]/div/header/div[1]/section/div/ul/li[1]/button")
    if loginBtns:
        #loginBtns[0].click()
        driver.execute_script('arguments[0].click()', loginBtns[0])
    else:
        print('Could not find login button.')
finally:
    driver.quit()
猜你喜欢
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2021-02-01
  • 2017-06-14
  • 1970-01-01
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多