下面是我的代码:
from selenium import webdriver
from selenium.webdriver.common.by import By
op_path: str = r"D:\Coding\Python\Projekte\Minecraft Updater\stuff\chromedriver.exe"
driver=webdriver.Chrome(op_path)
driver.get('https://www.curseforge.com/minecraft/mc-mods')
driver.implicitly_wait(10)
driver.find_element(By.XPATH, '//button[text()="Akeptieren"]').click()
我正在尝试抓取https://www.curseforge.com/minecraft/mc-mods,然而页面首先要求我同意某种cookie隐私的事情。我尝试过的所有“接受”按钮的定位器似乎都不起作用。在尝试搜索按钮之前,我确保覆盖已经弹出,但即使这样,它也抛出了一个“没有这样的元素”的错误。
下面是accept按钮的HTML部分:
<button tabindex="0" title="Akzeptieren" aria-label="Akzeptieren" class="message-component message-button no-children buttons-row" path="[0,3,1]" style="padding: 10px 18px; margin: 10px; border-width: 1px; border-color: rgb(37, 53, 81); border-radius: 0px; border-style: solid; font-size: 14px; font-weight: 700; color: rgb(37, 53, 81); font-family: arial, helvetica, sans-serif; width: auto; background: rgb(255, 255, 255);">Akzeptieren</button>
我是HTML和selenium的新手,所以我很难理解如何点击这个该死的按钮!
发布于 2021-03-04 22:13:46
您的接受按钮在iframe中。
在Selenium中,您需要切换到该框架来访问内容,然后在访问完成后切换回来。要考虑同步问题,最好使用webdriver等待。更多关于Selenium的waits here的信息
这对我很管用
driver = webdriver.Chrome()
driver.get('https://www.curseforge.com/minecraft/mc-mods')
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[contains(@id,'sp_message_iframe')]")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Akeptieren']"))).click()
driver.switch_to_default_content()
##continue with your script
selenium文档建议不要混合使用隐式和显式等待。如果你更喜欢使用隐式的方法,这也是可行的:
driver = webdriver.Chrome()
driver.get('https://www.curseforge.com/minecraft/mc-mods')
driver.implicitly_wait(10)
iframe = driver.find_element_by_xpath("//iframe[contains(@id,'sp_message_iframe')]")
driver.switch_to.frame(iframe)
driver.find_element_by_xpath("//button[text()='Akeptieren']").click()
driver.switch_to_default_content()
##continue with your script
https://stackoverflow.com/questions/66473376
复制相似问题