Python和Selenium,尝试在网站结果中接受cookie:无法定位元素



我试图进入一个网站与python(硒)代码,我需要接受cookie。出于某种原因,无论我做了什么尝试,我总是得到这样的结果:无法定位元素。在网站的HTML代码"接受cookies按钮"下面。

<button tabindex="0" title="Hyväksy kaikki evästeet" aria-label="Hyväksy kaikki evästeet" class="message-component message-button no-children buttons-row" path="[0,3,1]">Hyväksy kaikki evästeet</button>

我试过以下方法:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
import pandas as pd 
import requests as req
class trackerBot(): 

def __init__(self):
self.driver = webdriver.Chrome()
# Tried with and without implicitly wait
self.driver.implicitly_wait(10)

def loadWebsite(self, uri):

self.driver.get(uri)
cookies_accept_btn = self.driver.find_element_by_xpath('/html/body/div/div[3]/div[5]/button[2]')
cookies_accept_btn.click()

def main():
bot = trackerBot()
bot.loadWebsite("https://www.tori.fi")        
return(0)

main()
谁能告诉我我错过了什么?提前感谢!

元素可以在iframe中。使用switch_to:通过Selenium和python切换到iframe

driver.switch_to.frame(iframe)

在find_element_by_xpath ("//button[@title='Hyväksy kaikki evästeet']")中试试

如果这不能解决您的问题,请参考本网站:

https://devhints.io/xpath

WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//button[@title='Hyväksy kaikki evästeet']"))).click()

使用Webdriver等待该元素,并通过xpath查找该元素的data-attribute标题。

进口
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC

"accept cookies"窗口位于iframe中,所以我必须切换到该框架才能找到该元素。使用以下代码完成切换:

iframe = self.driver.find_element(By.XPATH, '//iframe[@id="sp_message_iframe_433571"]')
self.driver.switch_to.frame(iframe)

此回答是作为对问题的编辑发布的,试图在网站结果中接受cookie:无法通过OP Böhmeli在CC by - sa 4.0下定位元素。

最新更新