如何使用Selenium自动化Email Hunter Chrome扩展?
如何使用Selenium自动化Email Hunter Chrome扩展?
我来帮你搞定这个问题!先看看你当前代码里的问题,再给你两种可行的解决方案:
一、先修复你现有代码的错误
你现在遇到的OSError是因为传错了文件路径:你定义了fnExtensionIcon是扩展图标的图片路径,但在pyautogui.locateOnScreen里却用了fnExtension(也就是crx插件文件的路径),pyautogui没法把crx文件当成图片来识别,自然报错了。
只需要把这一行:
img_location = pyautogui.locateOnScreen(fnExtension, confidence=0.5)
改成:
img_location = pyautogui.locateOnScreen(fnExtensionIcon, confidence=0.5)
这样pyautogui就能正确识别你准备的扩展图标图片了。不过这种依赖屏幕截图的方法有个缺点:如果屏幕分辨率变了、浏览器窗口位置移动了,都可能导致定位失败,所以更推荐下面这种纯Selenium的方案。
二、更稳定的纯Selenium自动化方案
不用pyautogui,直接通过DOM元素定位来操作扩展,步骤如下:
- 打开Chrome的扩展面板:定位浏览器右上角的扩展按钮,点击展开所有已安装的扩展。
- 定位并点击Email Hunter扩展:在扩展列表里找到Email Hunter的入口,点击打开它的弹窗。
- 提取邮箱数据:定位弹窗里展示邮箱的元素,获取它的文本内容。
修改后的代码示例:
import os, sys from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC path = os.path.abspath(os.path.dirname(sys.argv[0])) fnExtension = os.path.join(path, "EmailHunter.crx") print(f"Checking Browser driver...") options = Options() options.add_argument("start-maximized") options.add_argument('--log-level=3') options.add_extension(fnExtension) options.add_experimental_option("prefs", {"profile.default_content_setting_values.notifications": 1}) options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('excludeSwitches', ['enable-logging']) options.add_experimental_option('useAutomationExtension', False) options.add_argument('--disable-blink-features=AutomationControlled') srv=Service() driver = webdriver.Chrome(service=srv, options=options) waitWD = WebDriverWait(driver, 10) # 打开目标网站 link = "https://www.orf.at" driver.get(link) # 1. 点击Chrome右上角的扩展按钮 extension_button = waitWD.until(EC.element_to_be_clickable((By.XPATH, "//button[@aria-label='Extensions']"))) extension_button.click() # 2. 定位并点击Email Hunter扩展(根据扩展标题定位,你可以根据实际情况调整选择器) email_hunter_ext = waitWD.until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@title, 'Email Hunter')]"))) email_hunter_ext.click() # 3. 等待弹窗加载,提取邮箱数据(这里的选择器需要你自己检查弹窗的DOM结构,替换成实际的元素路径) email_box = waitWD.until(EC.presence_of_element_located((By.CSS_SELECTOR, "这里替换成展示邮箱的元素选择器"))) emails = email_box.text print("提取到的邮箱:", emails) # 后续操作... # driver.quit()
注意事项:
- 扩展弹窗的元素选择器需要你自己用Chrome开发者工具(F12)去检查,替换代码里的占位符。
- 如果扩展打开的是新标签页而不是弹窗,你需要切换到对应的标签页再提取数据。
备注:内容来源于stack exchange,提问作者Rapid1898
相关产品推荐
相关产品推荐

