selenium 的一些常用设置

我默认用的是Chrome浏览器

一、安装selenium和配置Chromedriver

1、安装selenium,直接使用pip安装

pip install selenium

2、chromedriver下载地址:
https://sites.google.com/a/chromium.org/chromedriver/downloads (需要翻墙)
http://npm.taobao.org/mirrors/chromedriver/(阿里的)

注意事项 :chromedriver的版本要与你电脑使用的chrome版本对应,对应关系如下:

ChromeDriver v74.0.3729.6 (2019-03-14) Supports Chrome v74
ChromeDriver v2.46 (2019-02-01) Supports Chrome v71-73
ChromeDriver v2.45 (2018-12-10) Supports Chrome v70-72
ChromeDriver v2.44 (2018-11-19) Supports Chrome v69-71
ChromeDriver v2.43 (2018-10-16) Supports Chrome v69-71
ChromeDriver v2.42 (2018-09-13) Supports Chrome v68-70

chromedriver版本 支持的Chrome版本
v2.41 v67-69
v2.40 v66-68
v2.39 v66-68
v2.38 v65-67
v2.37 v64-66
v2.36 v63-65
v2.35 v62-64
v2.34 v61-63
v2.33 v60-62
v2.32 v59-61
v2.31 v58-60
v2.30 v58-60
v2.29 v56-58
v2.28 v55-57
v2.27 v54-56
v2.26 v53-55
v2.25 v53-55
v2.24 v52-54
v2.23 v51-53
v2.22 v49-52
v2.21 v46-50
v2.20 v43-48
v2.19 v43-47
v2.18 v43-46
v2.17 v42-43
v2.13 v42-45
v2.15 v40-43
v2.14 v39-42
v2.13 v38-41
v2.12 v36-40
v2.11 v36-40
v2.10 v33-36
v2.9 v31-34
v2.8 v30-33
v2.7 v30-33
v2.6 v29-32
v2.5 v29-32
v2.4 v29-32

下载完成后:
windows 下,新建一个命名为chromedriver文件夹,将解压的chromedriver.exe放进文件夹,再配置进path环境变量
Linux下,把下载好的文件放在 /usr/bin 目录下就可以了。

二、浏览器的有界面和无界面设置

1、 有界面

opt = webdriver.Chrome()

2、使用headless无界面浏览器模式

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
# 启动浏览器,获取网页源代码
opt = webdriver.Chrome(chrome_options=chrome_options)

三、不加载图片设置

# 不加载图片设置
options = webdriver.ChromeOptions()
prefs = {   'profile.default_content_setting_values' : { 'images': 2  }	}
options.add_experimental_option('prefs',prefs)
opt = webdriver.Chrome(chrome_options = options)

四、selenium定位之iframe中的元素定位

1.iFrame有ID 或者 name的情况
//进入id="frame1"的frame中,定位id="div1"的div和id="input1"的输入框。
dr.switchTo().frame(“frame1”);
dr.findElement(By.id(“div1”));
dr.findElement(By.id(“input1”))

2.如果一个iFrame既没有id,也没有name,通用情况
// 定位frame位置,并选取frame
WebElement frame=driver.findElement(By.xpath( “/html/body/div[2]/div[8]/div[2]/div[3]/div/div[2]/div/iframe” ));
driver.switchTo().frame(frame);

3.跳出iFrame
//跳出frame,进入default content;重新定位id="id1"的div
dr.switchTo().defaultContent();
dr.findElement(By.id(“id1”))

参考的网站有:
https://www.cnblogs.com/lijuanfei/p/10372651.html
https://www.cnblogs.com/wuhl-89/p/9453885.html
https://blog.csdn.net/yoyocat915/article/details/80580066
https://blog.csdn.net/ircszwfcbvdgk234/article/details/78605052
https://blog.csdn.net/zin521/article/details/82177874
http://blog.sina.com.cn/s/blog_68f262210101mcxp.html

猜你喜欢

转载自blog.csdn.net/weixin_42081389/article/details/89878885