Python Selenium脚本无法在Headless中正常运行,但在没有Headless的情况下可以运行

时间:2019-11-28 02:13:30

标签: python selenium google-chrome-headless

我当前的任务是使用Python和Selenium检查呼叫中心电话线的状态,如果电话线有错误,它将通过Slack发送屏幕截图。

程序的工作方式如下:

  1. 打开登录页面并登录系统
  2. 打开PhoneStatus页面并遍历表格以检查每个电话线路状态
  3. 获取截图并在电话线不工作时向Slack发送消息

代码

def open_browser(url):

    # Current Time
    curr_time = datetime.now().strftime("%H%M%S")

    # Current Date
    curr_date = datetime.today().strftime('%d%m%Y')

    # Counters
    offcount = 0
    oncount = 0
    offlinecount = 0

    # Options for chrome to run Headless (No Browser will popup)
    browser_options = webdriver.ChromeOptions()
    # browser_options.add_argument('--headless')
    browser_options.add_argument('window-size=1980x1080')

    browser = webdriver.Chrome(
        executable_path='driverlocation', 
        options=browser_options)
    browser.get(url)

    browser.implicitly_wait(10)

    # Enter username
    username = browser.find_element_by_xpath("//input[@name='username'][@id='loginname']")
    username.send_keys('username')

    # Enter password
    password = browser.find_element_by_xpath("//input[@name='password'][@id='loginpass']")
    password.send_keys('password')

    # Click login
    login = browser.find_element_by_xpath("//input[@id='login_button'][@value='Login']")
    login.send_keys(Keys.ENTER)

    # Wait for web browser to load all components
    browser.implicitly_wait(10)

    # Opens new window
    browser.get('http://link/to/phoneStatus.htm')

    # Wait for web browser to load components
    browser.implicitly_wait(10)

    # Loop through table
    table = browser.find_element_by_css_selector('table.tblcontext tbody')
    for row in table.find_elements_by_css_selector('tr'):
        for data in row.find_elements_by_css_selector('td'):
            if data.text == 'OffHook':
                offcount += 1
            elif data.text == 'OnHook':
                oncount += 1
            elif data.text == 'Offline':
                offlinecount += 1

    print('Offline Count: ' + str(offlinecount))
    print('OnHook Count: ' + str(oncount))
    print('OffHook Count: '+ str(offcount))

    # Sends message to Slack if count is more than 0
    if offlinecount > 0:
        image_name = curr_date+'_'+curr_time+'.png'
        browser.save_screenshot('C:\\PythonProjects\\PhoneCheckAutomation\\'+image_name)
        # message.send_message(image_name)

    browser.quit()

该代码可以正常工作,但是一旦browser_options.add_argument('--headless')行未注释,该代码甚至无法在登录页面上运行,更不用说第二页了。

我尝试根据我看到的一些答案设置窗口大小,但仍然无法正常工作。

我还能尝试其他什么吗?

1 个答案:

答案 0 :(得分:0)

# Options for chrome to run Headless (No Browser will popup)
browser_options = webdriver.ChromeOptions()
# browser_options.add_argument('--headless')

browser = webdriver.Chrome(
    executable_path='driverlocation', 
    options=browser_options)
browser.set_window_size(1920, 1080)
browser.get(url)