Python+Selenium+Chrome 笔记(2)Selenium的Hello World

在上一篇文章配置好 Selenium 和 Chrome Driver 后,我们该来了学习一下 Selenium 了。

在此之前我先简单介绍一下Selenium调用Chrome Drive的几个常用的参数设置:
1、不加载图片
2、不使用GUI(handless,也就是不打开Chrome的界面,后台运行,这样子的话在服务器上很好用)

代码如下:

from selenium import webdriver

PicLoad = False  #这里设置是否加载图片
GUILoad = True  #这里设置是否启动GUI

chrome_options = webdriver.ChromeOptions()  #初始化chrome的options

#加载图片设置
if not PicLoad:
    prefs = {"profile.managed_default_content_settings.images": 2}
    chrome_options.add_experimental_option("prefs", prefs)

#加载GUI设置
if not GUILoad:
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')

在完成了Chrome Driver的设置之后,我们就可以开始学习Selenium的函数了。
首先我们打开一个网站,以百度的主页为例:

driver = webdriver.Chrome(chrome_options=chrome_options)  #初始化webdriver
driver.get('https://www.baidu.com/')  #打开百度的页面

打开页面之后,我们先开始寻找我们要抓取或者进行操作的元素。
Selenium提供了八种定位方式:
id , name , class name , tag name ,link text , partial link text , xpath , css selector
调用的方法也比较相似。
假设我们要实现在百度页面的输入框输入文字并且进行搜索。

我们先定位到搜索框:
这里有很多种定位方式,我举例两种:

dr.find_element_by_id("kw")  #通过id定位

或者

elem = driver.find_element_by_xpath('//*[@id="kw"]')  #通过xpath定位

虽然两种方式都是按他的id定位的…
这里我简单提一下xpath的快速获取方式:
可以在Chrome中右键Copy Xpath


xpath获取

下面开始介绍Selenium的一些基本的操作函数:

方法 功能
set_window_size() 设置浏览器的大小
back() 控制浏览器后退
forward() 控制浏览器前进
refresh() 刷新当前页面
clear() 清除文本
send_keys (value) 模拟按键输入
click() 单击元素
submit() 用于提交表单
get_attribute(name) 获取元素属性值
is_displayed() 设置该元素是否用户可见
size 返回元素的尺寸
text 获取元素的文本

我们要定位到了输入的表单,现在要给他输入一个搜索的关键字并回车,代码如下:

elem.send_keys('Hello world!')
elem.send_keys(Keys.RETURN)

其中的 Keys.RETURN 要在文件中先import

from selenium.webdriver.common.keys import Keys

然后我们再打开第一个链接:

elem = driver.find_element_by_xpath('//*[@id="1"]/h3/a')
elem.click()

Selenium的基本操作就到这里了。
附上完整代码:

#coding:utf-8

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

PicLoad = True
GUILoad = True

chrome_options = webdriver.ChromeOptions()
if not PicLoad:
    prefs = {"profile.managed_default_content_settings.images": 2}
    chrome_options.add_experimental_option("prefs", prefs)
if not GUILoad:
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')

driver = webdriver.Chrome(chrome_options=chrome_options)

driver.get('https://www.baidu.com/')
elem = driver.find_element_by_name('wd')
elem.send_keys('Hello world!')
elem.send_keys(Keys.RETURN)
time.sleep(1)
elem = driver.find_element_by_xpath('//*[@id="1"]/h3/a')
elem.click()

感谢:
https://blog.csdn.net/qq_36962569/article/details/77200118
https://blog.csdn.net/weixin_36279318/article/details/79475388

你可能感兴趣的:(Python+Selenium+Chrome 笔记(2)Selenium的Hello World)