linux 下selenium chrome使用详解

脚本专栏 发布日期:2024/10/22 浏览次数:1

正在浏览:linux 下selenium chrome使用详解

安装chrome

wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
yum install ./google-chrome-stable_current_x86_64.rpm
yum install mesa-libOSMesa-devel gnu-free-sans-fonts wqy-zenhei-fonts

安装chromedriver

淘宝源(推荐)

wget http://npm.taobao.org/mirrors/chromedriver/2.41/chromedriver_linux64.zip
unzip chromedriver_linux64.zip
move chromedriver /usr/bin/
chmod +x /usr/bin/chromedriver

编写selenium自动化脚本

#!/usr/bin/python
# -*-coding:utf-8-*-

import re, os
import json
import time
import random
import requests
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.wait import TimeoutException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.select import Select

binary_location = '/usr/bin/google-chrome'
chrome_driver_binary = '/usr/bin/chromedriver'

chrome_options = Options()
chrome_options.binary_location = binary_location
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--disable-dev-shm-usage')

chromedriver = chrome_driver_binary
os.environ["webdriver.chrome.driver"] = chromedriver

BROWSER = webdriver.Chrome(executable_path='/usr/bin/chromedriver', chrome_options=chrome_options)

WAIT = WebDriverWait(BROWSER, 5)
URL = "http://www.baidu.com"
BROWSER.get(URL)
..........

踩到的坑一:

中文乱码,解决方法:

centos:

yum groupinstall fonts

ubuntu:

sudo apt-get install ttf-wqy-microhei ttf-wqy-zenhei xfonts-wqy

踩到的坑二:

不能截图,抛time out异常

selenium.common.exceptions.TimeoutException: Message: timeout: Timed out receiving message from renderer: 10.000

解决方法:

options = webdriver.ChromeOptions()
options.add_argument("--headless")
options.add_argument("start-maximized")
options.add_argument("enable-automation")
options.add_argument("--no-sandbox")
options.add_argument("--disable-infobars")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-browser-side-navigation")
options.add_argument("--disable-gpu")
driver = webdriver.Chrome(chrome_options=options)
driver.set_window_size(1024, 768)
driver.get_screenshot_as_file(STATIC_FOLDER + home_img_url)
driver.close()
一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?