如何解决Selenium无法找到元素,因此无法单击按钮
我试图使我的脚本单击Spotify Checkout Page上的“购买/购买家庭”按钮。无论是什么类,CSS,XPath,ID或我输入的任何内容,都只是说它找不到对象。
这是按钮。它不在iframe中:
<div class="sc-fzXfOu cvoJMt">
<button id="checkout_submit" class="Button-oyfj48-0 kaOWUo sc-fzXfOv tSdMK">
Buy Premium Family
</button>
</div>
我的代码:
time.sleep(3)
buy = driver.find_element_by_xpath("/html/body/div[3]/div/div/div/div/div/div/div[3]/div/div/div[2]/form/div[2]/button").click()
解决方法
我可以通过其他xpath单击按钮 driver.findElement(By.xpath(“ // button [@ id ='checkout_submit']”)))。click();
编辑-
仅当我最初加载页面并且dom中没有任何更改时,您的xpath才对我有用-/html/body/div[3]/div/div/div/div/div/div/div[3]/div/div/div[2]/form/div[2]/button
当显示一些新事件或错误并且dom结构发生更改时,此功能将无效。
当元素具有可区分的属性时,为什么要使用这种相对的XPath?
,这里的问题是表格不是静态的,您必须等待所有元素的加载。
页面会加载窗格以接受可以掩盖要对其执行操作的元素的cookie。
在这种情况下,最好的方法是先接受Cookie,然后执行所需的所有操作。
请尝试使此代码适应您的需求,并在我的测试中成功运行。
如果您运行此代码,则当驱动程序获取页面时,必须先停止执行才能登录。
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.remote.webelement import WebElement
# change this line
path_driver = "your_path_to_chrome_driver"
by,buy_selector,cookies_selector = By.CSS_SELECTOR,'button#checkout_submit',"button#onetrust-accept-btn-handler"
driver = webdriver.Chrome(path_driver)
driver.maximize_window()
actions = ActionChains(driver)
driver.get("https://www.spotify.com/us/purchase/offer/premium-family/?country=US")
# wait for loading buy button
sls = wait.until(EC.presence_of_all_elements_located((by,buy_selector)))
if sls:
# get accept cookies button element and click
cookies_accept = driver.find_element_by_css_selector(cookies_selector)
if isinstance(cookies_accept,WebElement):
cookies_accept.click()
# get buy button element,move to element and click
buy = driver.find_element_by_css_selector(buy_selector)
if isinstance(buy,WebElement) and buy.is_displayed() and buy.is_enabled():
actions.move_to_element(buy).click(buy).perform()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。