[英]Python and Selenium, Trying to accept cookies on website results: Unable to locate element
我正在尝试进入一个带有 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()
有人可以建议我缺少什么吗? 提前谢谢了!
在 find_element_by_xpath ("//button[@title='Hyväksy kaikki evästeet']") 中试试这个
如果这不能解决您的问题,请参考本网站:
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
该元素可能位于 iframe 中。 使用 switch_to: 通过 Selenium 和 python 切换到 iframe
driver.switch_to.frame(iframe)
“接受 cookies 窗口”位于 iframe 中,因此我必须切换到该框架才能找到该元素。 使用以下代码完成切换:
iframe = self.driver.find_element(By.XPATH, '//iframe[@id="sp_message_iframe_433571"]')
self.driver.switch_to.frame(iframe)
此答案作为对已解决问题Python 和 Selenium的编辑发布,尝试在网站结果上接受 cookies:无法通过 CC Böhmeli在 CC BY-SA 4.0 下定位元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.