解决了Python和Selenium问题,尝试接受网站上的Cookie结果:无法定位元素

2024-04-25 20:19:35 发布

您现在位置:Python中文网/ 问答频道 /正文

解决方法:“接受cookies窗口”位于iframe中,因此我必须切换到该框架才能找到元素。使用以下代码进行切换:

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

原始问题:

我试图进入一个带有python(selenium)代码的网站,我必须接受cookies。出于某种原因,无论我尝试了什么,我总是得到这样的结果:无法定位元素。下面是网站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()

有人能告诉我遗漏了什么吗? 非常感谢


Tags: 代码fromimportselfmessagedriverseleniumbutton
3条回答

在find_element_by_xpath(//button[@title='Hyväksy kaikki evästeet'])中尝试这个方法

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

https://devhints.io/xpath

该元素可能位于iframe中。 使用开关_可以: Switch to an iframe through Selenium and python

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

使用Webdriver等待元素并通过xpath查找元素及其数据属性标题

进口

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

相关问题 更多 >