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

编程知识 更新时间:2023-04-22 10:45:09

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

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

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

# 本地Chrome浏览器设置方法
from selenium import  webdriver 
import time

driver = webdriver.Chrome() 
driver.get('https://localprod.pandateacher/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:通过元素的名称选择
# 如<h1>你好,蜘蛛侠!</h1> 
# 可以使用find_element_by_tag_name('h1')

find_element_by_class_name:通过元素的class属性选择
# 如<h1 class="title">你好,蜘蛛侠!</h1>
# 可以使用find_element_by_class_name('title')

find_element_by_id:通过元素的id选择
# 如<h1 id="title">你好,蜘蛛侠!</h1> 
# 可以使用find_element_by_id('title')

find_element_by_name:通过元素的name属性选择
# 如<h1 name="hello">你好,蜘蛛侠!</h1> 
# 可以使用find_element_by_name('hello')

#以下两个方法可以提取出超链接

find_element_by_link_text:通过链接文本获取超链接
# 如<a href="spidermen.html">你好,蜘蛛侠!</a>
# 可以使用find_element_by_link_text('你好,蜘蛛侠!')

find_element_by_partial_link_text:通过链接的部分文本获取超链接
# 如<a href="https://localprod.pandateacher/python-manuscript/hello-spiderman/">你好,蜘蛛侠!</a>
# 可以使用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,在后台默默运行

更多推荐

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

本文发布于:2023-04-17 02:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/8b387c584e9f3f01d8c07dd9ac4c7309.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浏览器   操作   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 82262文章数
  • 6664阅读数
  • 0评论数