如何使用selenium e tor按下“不可见”按钮,但知道html id?

carvr3hs  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(322)

在firefox中使用selenium和webdriverwait,我想按下“接受”按钮。在普通浏览器上,按钮屏幕显示正常,但问题是我正在使用tor访问站点,因此按钮屏幕显示为暗显/暗显阴影:它无限期加载,从不显示。o就好像按钮从未被检测到。事实上,在python控制台中,我得到了错误“selenium.common.exceptions.timeoutexception:message”,因为秒过了,但没有找到按钮。我还试着直接打开tor浏览器(没有python和代码),结果是一样的:模糊的按钮掩码
我读到,通过直接干预代码,即使不可见也可以按下按钮。我该怎么办?我重复一遍,在普通浏览器中,按钮就在那里,但在tor中,它变暗了。可能我想一直使用webdriverwait。我真诚地感谢任何帮助我的人。我将非常感谢任何善意的回应
按钮的html代码是onetrust accept btn处理程序,确切地说是:

带有普通浏览器按钮的页面为:

带有tor和空白/封闭屏幕的页面为:

这是我的代码:

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

# CODE TOR CONNECTION

from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
import os

torexe = os.popen('/home/mypc/.local/share/torbrowser/tbb/x86_64/tor-browser_en-US') 

profile = FirefoxProfile('/home/mypc/.local/share/torbrowser/tbb/x86_64/tor-browser_en-US/Browser/TorBrowser/Data/Browser/profile.default')
profile.set_preference('network.proxy.type', 1)
profile.set_preference('network.proxy.socks', '127.0.0.1')
profile.set_preference('network.proxy.socks_port', 9050)
profile.set_preference("network.proxy.socks_remote_dns", False)
profile.update_preferences()

firefox_options = webdriver.FirefoxOptions()
firefox_options.binary_location = '/usr/bin/firefox' 

driver = webdriver.Firefox(
    firefox_profile=profile, options=firefox_options, 
    executable_path='/usr/bin/geckodriver') 

# CODE CLICK BUTTON

driver.maximize_window()
driver.get("link")
WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "onetrust-accept-btn-handler"))).click()

我使用了元素的presence_of_element_located(),这是检查页面dom中是否存在元素的期望值。这并不一定意味着元素是可见的。
我也试着用它

element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[id='onetrust-accept-btn-handler']")))

WebDriverWait(driver,15).until(EC.element_to_be_clickable((By.XPATH,"//button[@class='onetrust-accept-btn-handler')]"))).click()

我总是在每个人身上犯同样的错误,selenium.common.exceptions.timeoutexception:message“因为秒过了,但没有找到按钮。

aij0ehis

aij0ehis1#

尝试等待元素出现,然后用javascript而不是selenium单击它。这样地:

WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.ID, "onetrust-accept-btn-handler")))
driver.execute_script("document.getElementsById('onetrust-accept-btn-handler')[0].click()")

javascript能够访问不可见的元素。这不会通过gui完全模拟真实的用户手动操作,但会起作用。

相关问题