linux selenium chrome 加载用户配置文件

发布时间:2020-06-01 17:07:00编辑:Run阅读(4309)

    linux selenium chrome 加载用户配置文件


    需要安装linux桌面环境(系统版本: CentOS Linux release 7.6.1810 (Core))

    yum groupinstall "GNOME Desktop" "Graphical Administration Tools"


    获取当前系统启动模式

    [root@crawler-03 etc]# systemctl get-default

    multi-user.target


    查看配置文件


    [root@crawler-03 etc]# cat /etc/inittab 

    # inittab is no longer used when using systemd.

    # ADDING CONFIGURATION HERE WILL HAVE NO EFFECT ON YOUR SYSTEM.

    # Ctrl-Alt-Delete is handled by /usr/lib/systemd/system/ctrl-alt-del.target

    # systemd uses 'targets' instead of runlevels. By default, there are two main targets:

    # multi-user.target: analogous to runlevel 3

    # graphical.target: analogous to runlevel 5

    # To view current default target, run:

    # systemctl get-default

    # To set a default target, run:

    # systemctl set-default TARGET.target


    设置桌面方式启动

    systemctl set-default TARGET.target


    启动服务器

    reboot


    linux安装google浏览器

    wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm

    yum install ./google-chrome-stable_current_*.rpm


    google在linux中运行需要添加--no-sandbox

    which google-chrome

    vim /bin/google-chrome

    exec -a "$0" "$HERE/chrome" "$@" --no-sandbox


    安装google驱动

    wget https://chromedriver.storage.googleapis.com/81.0.4044.69/chromedriver_linux64.zip

    unzip chromedriver_linux64.zip 

    mv chromedriver /usr/bin/chromedriver

    chmod +x /usr/bin/chromedriver


    用VNC或者xmanager连接linux桌面(方式自行baidu)

    打开google浏览器,访问chrome://version/

    image.png


    /root/.config/google-chrome/Default 就是用户配置文件了


    首先手动登录下百度,然后通过selenium headless无头模式,加载本地用户配置文件免登陆

    代码如下:

    from selenium import webdriver
    import time
    
    option = webdriver.ChromeOptions()
    option.add_argument('--headless')
    option.add_argument('--no-sandbox')
    option.add_argument('--disable-gpu')
    option.add_argument('--disable-infobars')
    option.add_argument('--start-maximized')
    option.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36')
    # linux
    option.add_argument(r'--user-data-dir=/root/.config/google-chrome')
    option.add_argument(r'--profile-directory=Default')
    browser = webdriver.Chrome(chrome_options=option)
    url = 'https://www.baidu.com'
    try:
        browser.get(url)
        browser.implicitly_wait(120)
        userinfo = browser.find_element_by_xpath("//span[@class='user-name c-font-normal c-color-t']").text
        print("userinfo:{}".format(userinfo))
        time.sleep(3)
    except Exception as e:
        print(e)
    browser.quit()









关键字