Selenium浏览器启动方式

Chromedriver所有版本下载
原文链接

浏览器的基本操作

  1. 普通方式启动浏览器:
python 复制代码
from selenium import webdriver
# 启动Chrom浏览器
browser = webdriver.Chrome()
# 启动Edge浏览器
browser = webdriver.Edge()
# 启动Firefox浏览器
browser = webdriver.Firefox()
browser.get('http://www.baidu.com/')
  1. Headless方式启动(无界面启动)
    Headless Chrome 是 Chrome 浏览器的无界面形态,可以在不打开浏览器的前提下,使用所有 Chrome 支持的特性运行你的程序。
python 复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
chrome_options = webdriver.ChromeOptions()
# 使用headless无界面浏览器模式
chrome_options.add_argument('--headless') # 增加无界面选项
chrome_options.add_argument('--disable-gpu') # 如果不加这个选项,有时定位会出现问题
# 启动浏览器,获取网页源代码
browser = webdriver.Chrome(chrome_options=chrome_options)
mainUrl = "https://www.taobao.com/"
browser.get(mainUrl)
print(f"browser text = {browser.page_source}")
browser.quit()
  1. 加载配置文件方式启动
    Selenium默认是不加载配置启动,用Chrome地址栏输入chrome://version/,查看自己的"个人资料路径",然后在浏览器启动时,调用这个配置文件,代码如下:
python 复制代码
from selenium import webdriver
option = webdriver.ChromeOptions()
option.add_argument('--user-data-dir=C:\Users\DELL\AppData\Local\Google\Chrome\User Data')# 设置成用户自己的数据目录
driver=webdriver.Chrome(chrome_options=option)

元素定位

  1. 常见的元素定位方式
python 复制代码
#通过id方式定位
browser.find_element_by_id("kw").send_keys("selenium")
#通过name方式定位
browser.find_element_by_name("wd").send_keys("selenium")
#通过tag name方式定位
browser.find_element_by_tag_name("input").send_keys("selenium")
#通过class name方式定位
browser.find_element_by_class_name("s_ipt").send_keys("selenium")
#通过CSS方式定位
browser.find_element_by_css_selector("#kw").send_keys("selenium")
#通过xpath方式定位
browser.find_element_by_xpath("//input[@id='kw']").send_keys("selenium")
相关推荐
站大爷IP27 分钟前
Python文件操作的"保险箱":with语句深度实战指南
python
运器12334 分钟前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
巴里巴气3 小时前
selenium基础知识 和 模拟登录selenium版本
爬虫·python·selenium·爬虫模拟登录
19893 小时前
【零基础学AI】第26讲:循环神经网络(RNN)与LSTM - 文本生成
人工智能·python·rnn·神经网络·机器学习·tensorflow·lstm
JavaEdge在掘金3 小时前
Redis 数据倾斜?别慌!从成因到解决方案,一文帮你搞定
python
ansurfen3 小时前
我的第一个AI项目:从零搭建RAG知识库的踩坑之旅
python·llm
前端付豪3 小时前
20、用 Python + API 打造终端天气预报工具(支持城市查询、天气图标、美化输出🧊
后端·python
前端付豪3 小时前
19、用 Python + OpenAI 构建一个命令行 AI 问答助手
后端·python
amazinging4 小时前
北京-4年功能测试2年空窗-报培训班学测开-第四十三天
python·学习
wgyang20164 小时前
我的第一个LangFlow工作流——复读机
python