selenium 是python的一个库,可以很方便的调用浏览器驱动,实现代码操控浏览器。
最近一直中利用业余时间在研究这个,今天分享给大家。
使用一个有道翻译进行案例吧。直接上代码。
'''
根据chrome浏览器2017年发布的新特性,
需要unix版本的chrome版本高于57,
windows版本的chrome版本高于58,
才能使用无界面运行.
'''
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import ActionChains
import time
input_txt = "今天天气不错,挺风和日丽的,我们下午不上班,情挺好的,你呢好不好啊." # 需要翻译的内容
chrome_opt = Options() # 创建参数设置对象.
chrome_opt.add_argument('--headless') # 无界面化.
chrome_opt.add_argument('--disable-gpu') # 配合上面的无界面化.
chrome_opt.add_argument('--window-size=1366,768') # 设置窗口大小, 窗口大小会有影响.
chrome_opt.add_argument("--no-sandbox") # ubuntu没有报错是因为不是以root用户登录的。
# 创建Chrome对象并传入设置信息.
driver = webdriver.Chrome(executable_path=“chromedriver.exe”, options =chrome_opt)
# 操作这个对象.
driver.get('http://fanyi.youdao.com/') # get方式访问有道翻译.
time.sleep(2)
element_input_txt = driver.find_element_by_id("