我正在尝试禁用一个特定网站的广告块,但我找不到一个方法来做。我尝试在selenium documentation中查找,但之后找不到任何禁用扩展的方法。但是,我在阅读文档方面还是个新手,所以我可能遗漏了一些东西。我还尝试使用selenium自动禁用AdBlock扩展,但没有成功。计划是去chrome的扩展部分(chrome://扩展/),获取“enabled”复选框并单击它,而无需我的干预。以下是我的尝试:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import StaleElementReferenceException
def main():
opening = True
while opening:
try:
chrome_options = Options()
#Path to AdBlock
chrome_options.add_extension('/usr/local/bin/AdBlock_v.crx')
driver = webdriver.Chrome(chrome_options=chrome_options)
except:
print('An unkown error has occured. Trying again...')
else:
opening = False
disable_adblocker(driver)
def click_element(driver, xpath, index):
getting = True
not_found_times = 0
while getting:
try:
getting = False
element = WebDriverWait(driver, 5).until(
EC.presence_of_all_elements_located((By.XPATH,xpath)))[index]
element.click()
#driver.get(element.get_attribute("href"))
#In case the page does not load properly
except TimeoutException:
not_found_times += 1
if not_found_times < 2:
driver.refresh()
getting = True
else:
raise
#In case DOM updates which makes elements stale
except StaleElementReferenceException:
getting = True
def disable_adblocker(driver):
driver.get('chrome://extensions')
ad_blocker_xpath = '//div[@id="gighmmpiobklfepjocnamgkkbiglidom"]//div[@class="enable-controls"]//input'
click_element(driver,ad_blocker_xpath,0)
print('')
main()
我的尝试失败的原因是selenium无法使用我指定的xpath来获取checkbox元素。我相信这条路是正确的。在
我能想到的唯一解决方案是创建两个chrome窗口:一个带有AdBlock,另一个没有AdBlock。不过,我不想要两个窗口,因为这会使事情变得更复杂。在
使用selenium中的任何设置都不可能实现这一点。然而。。。您可以在创建驱动程序后自动添加要排除的域。在
在测试真正开始之前,但是在初始化浏览器之后,导航到chrome扩展://[your AdBlock extension ID]/选项.html. AdBlock扩展标识对于crx文件是唯一的。所以进入chrome并在扩展管理器中找到值。例如,我的是gighmmpiobklfepjocnamgkkbiglidom。在
导航到该页面后,单击“自定义”,然后单击“显示除这些域以外的所有位置的广告…”,然后在字段中输入域,然后单击“确定”。繁荣!现在域名被添加,并将显示广告!只要确定一下
我知道这不是理想的快速,简单,一行代码的解决方案。。。但这似乎是最好的选择,除非你想去挖掘本地存储文件并找到这些数据被添加到哪里。。。在
相关问题 更多 >
编程相关推荐