python实现控制浏览器,自动打开、输入、点击等操作 您所在的位置:网站首页 网页输入脚本怎么用 python实现控制浏览器,自动打开、输入、点击等操作

python实现控制浏览器,自动打开、输入、点击等操作

#python实现控制浏览器,自动打开、输入、点击等操作| 来源: 网络整理| 查看: 265

若想python实现控制浏览器,自动打开、输入、点击等操作,需要用到python的一个库,selenium 首先,和其它所有Python库一样,selenium需要安装,方法也很简单, 使用pip安装。

pip install selenium # Windows电脑安装selenium pip3 install selenium # Mac电脑安装selenium

selenium的脚本可以控制所有常见浏览器的操作,在使用之前,需要安装浏览器的驱动。 推荐使用Chrome浏览器,具体安装教程见下链接 https://localprod.pandateacher.com/python-manuscript/crawler-html/chromedriver/ChromeDriver.html 小例子:

# 本地Chrome浏览器设置方法 from selenium import webdriver import time driver = webdriver.Chrome() driver.get('https://localprod.pandateacher.com/python-manuscript/hello-spiderman/') time.sleep(2) teacher = driver.find_element_by_id('teacher') teacher.send_keys('必须是吴枫呀') assistant = driver.find_element_by_name('assistant') assistant.send_keys('都喜欢') time.sleep(1) button = driver.find_element_by_class_name('sub') time.sleep(1) button.click() time.sleep(1) driver.close()

selenium中常用方法 在这里插入图片描述

# 以下方法都可以从网页中提取出'你好,蜘蛛侠!'这段文字 find_element_by_tag_name:通过元素的名称选择 # 如你好,蜘蛛侠! # 可以使用find_element_by_tag_name('h1') find_element_by_class_name:通过元素的class属性选择 # 如你好,蜘蛛侠! # 可以使用find_element_by_class_name('title') find_element_by_id:通过元素的id选择 # 如你好,蜘蛛侠! # 可以使用find_element_by_id('title') find_element_by_name:通过元素的name属性选择 # 如你好,蜘蛛侠! # 可以使用find_element_by_name('hello') #以下两个方法可以提取出超链接 find_element_by_link_text:通过链接文本获取超链接 # 如你好,蜘蛛侠! # 可以使用find_element_by_link_text('你好,蜘蛛侠!') find_element_by_partial_link_text:通过链接的部分文本获取超链接 # 如你好,蜘蛛侠! # 可以使用find_element_by_partial_link_text('你好')

在这里插入图片描述

# 本地Chrome浏览器的静默模式设置: from selenium import webdriver #从selenium库中调用webdriver模块 from selenium.webdriver.chrome.options import Options # 从options模块中调用Options类 chrome_options = Options() # 实例化Option对象 chrome_options.add_argument('--headless') # 把Chrome浏览器设置为静默模式 driver = webdriver.Chrome(options = chrome_options) # 设置引擎为Chrome,在后台默默运行


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有