无法在无头的网页上定位元素 chrome

Unable to locate elements on webpage with headless chrome

我有一个访问打印机的脚本,当 chrome 通常是 运行 时,我的代码完全可以正常工作,但是当它是 运行 无头时,selenium 似乎无法找到网页上的元素。

相关代码如下:

初始化方法:

def __init__(self, ip_address):
    """ Initialize a new Printer_Webpage object."""
    self.ip_address = ip_address
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_argument("--window-size=1920x1080")
    self.browser = webdriver.Chrome(chrome_options=chrome_options)
    # Ignore lack of cert for each printer web page.
    # Otherwise, can't open page.
    self.browser.accept_untrusted_certs = True

登录方式:

def login(self):
    """Navigates through the login page for the printer."""
    # Open login page
    self.browser.get(f'https://{self.ip_address}/wcd/top.xml')
    # STEPS TO LOGIN:
    # 1) Select 'Administrator' radio button and click.
    self.browser.find_element_by_id('Admin').click()
    # 2) Select Login button and click.
    self.browser.find_element_by_xpath("//input[@type='submit' \
                                        and @value='Login']").click()
    # 3) Select admin (user mode)
    self.browser.find_element_by_id('R_ADM2').click()
    # 4) Select password field and input PASSWORD, then submit.
    password_field = self.browser.find_element_by_id('Admin_Pass')
    password_field.send_keys(PASSWORD)
    password_field.send_keys(Keys.RETURN)

完整错误信息:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"Admin"}

还有一些其他可能有用的信息:

(Session info: headless chrome=62.0.3202.94)

(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.14393 x86_64)

如果这是 SSL 证书的问题,您可以在没有证书的情况下使用命令行标志启动 Chrome(假设您是这样启动的)。我相信开关是 --allow-running-insecure-content,我从这个列表中找到 here.

@siking在评论中指出...

Chrome-headless does not work with invalid https certificates. You will only get a blank page! See http://bugs.chromium.org/p/chromium/issues/detail?id=721739

我遇到了同样的问题,发现元素在 headless 中加载速度较慢。 通过添加以下代码行,问题消失了:

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

我遇到了同样的情况。经研究,正确的是:

self.chrome_options = webdriver.ChromeOptions()
self.chrome_options.add_argument("--window-size=1920,1080")
self.chrome_options.add_argument("--disable-extensions")
self.chrome_options.add_argument("--proxy-server='direct://'")
self.chrome_options.add_argument("--proxy-bypass-list=*")
self.chrome_options.add_argument("--start-maximized")
self.chrome_options.add_argument('--headless')
self.chrome_options.add_argument('--disable-gpu')
self.chrome_options.add_argument('--disable-dev-shm-usage')
self.chrome_options.add_argument('--no-sandbox')
self.chrome_options.add_argument('--ignore-certificate-errors')
self.browser = webdriver.Chrome(options=self.chrome_options)

我遇到了同样的问题。您可以截屏以了解问题所在。

driver.get_screenshot_as_file("screenshot.png")

selenium 在 运行 正常工作但在无头模式下停止工作的几个原因 -

1)它可能已经切换到移动模板。可以通过更改 window 大小来修复。

chrome_options.add_argument("--window-size=1920,1080")

2)如果是空白页(截图),可能是因为 SSL 证书无效。(参见@Marcel_Wilson post)应该通过 -[=15= 修复]

chrome_options.add_argument('--ignore-certificate-errors')
chrome_options.add_argument('--allow-running-insecure-content')

3)可能网站屏蔽了'headless'模式。 (您的屏幕截图可能会显示您无法在正常模式下重现的错误) 你可以试试这个-

user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36'
options.add_argument(f'user-agent={user_agent}')

但是,如果网站有更强大的拦截方法,上述代码将无法工作。您可以在此处找到更多相关信息 https://intoli.com/blog/making-chrome-headless-undetectable/.

我确实遇到了这个问题,但下面的代码对我来说非常有效。

    final ChromeOptions options = new ChromeOptions();
    options.addArguments("--window-size=1920,1080");
    options.addArguments("--allow-insecure-localhost");
    options.addArguments("--headless");
    options.addArguments("--disable-gpu");
    options.addArguments("--no-sandbox");
    DesiredCapabilities caps = DesiredCapabilities.chrome();
    caps.setCapability(ChromeOptions.CAPABILITY, options);
    caps.setCapability("acceptInsecureCerts", caps);
    WebDriver driver = new ChromeDriver(options);

我有同样的问题,headless 不适用于某些网站和元素(显示空白页面内容,找不到元素等)。

这很可能是因为缺少 User-Agent 或 window 尺寸较小。添加以下参数:

"--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
"--window-size=1920x1080"

如果上述方法不起作用,还有另一种方法可以通过最小化 window 并将其移动到用户看不到的位置来“模拟”无头模式。

这不会从任务栏中隐藏 chrome 任务,但 Chrome 选项卡本身仍将为用户隐藏。

只需使用以下参数:

var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments(new List<string>() { "--window-size=1,1", "window-position=-2000,0" });  // This hides the chrome window

var chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;    // This is to hid the console.

ChromeDriver driver = new ChromeDriver(chromeDriverService, chromeOptions);
//driver.Manage().Window.Minimize(); //use this if the code above does not work
driver.Navigate().GoToUrl("https://google.com");

time.sleep(0.2) 帮我修好了。

我遇到了同样的问题。在无头模式下,找不到一个 webElement 并且 selenium 抛出带有错误的 NoSuchElementException:消息:没有这样的元素:无法找到元素。

为我修复的是添加 0.2 秒的等待时间,time.sleep(0.2) 上面的行定位了这个 webElement 并为我修复了它。

出于某种原因,在无头模式下加载此元素需要更多时间。