Myluzh Blog

Strive to become a dream architect.

python3+selenium实现web自动化

发布时间: 2021-3-5 文章作者: myluzh 分类名称: Python


0x01 Selenium安装
Selenium 的安装很简单,可采用如下方式。
pip3 install selenium
Selenium安装好之后,并不能直接使用,它需要与浏览器进行对接。这里拿Chrome浏览器为例。若想使用Selenium成功调用Chrome浏览器完成相应的操作,需要通过ChromeDriver来驱动。

0x02 ChromeDriver的安装
ChromeDriver的官方下载地址:https://chromedriver.storage.googleapis.com/index.html
下载之前先确认下我们使用的Chrome浏览器版本,找到与之对应的Chrome浏览器版本,根据你电脑系统的平台类型进行下载。
下载完成后解压,Windows将其放置在Python安装路径下Scripts文件夹中即可,macOS将chromedriver放置到/usr/local/bin/即可。

0x03 测试ChromeDriver
上述操作结束后,我们执行如下命令,测试一下
from selenium import webdriver
# 打开Chrome浏览器
browser = webdriver.Chrome()
代码执行后,若成功打开了浏览器,则证明你的ChromeDriver安装的没问题,可以正常愉快地使用Selenium了。

0x04 Selenium用法
#打开浏览器
browser = webdriver.Chrome()
#打开地址
browser.get("https://www.baidu.com")
Selenium定位方法
1.id定位:find_element_by_id(self, id_)
2.name定位:find_element_by_name(self, name)
3.class定位:find_element_by_class_name(self, name)
4.tag定位:find_element_by_tag_name(self, name)
5.link定位:find_element_by_link_text(self, link_text)
6.partial_link定位find_element_by_partial_link_text(self, link_text)
7.xpath定位:find_element_by_xpath(self, xpath)
8.css定位:find_element_by_css_selector(self, css_selector)
下面是复数形式
9.id复数定位find_elements_by_id(self, id)
10.name复数定位find_elements_by_name(self, name)
11.class复数定位find_elements_by_class_name(self, name)
12.tag复数定位find_elements_by_tag_name(self, name)
13.link复数定位find_elements_by_link_text(self, text)
14.partial_link复数定位find_elements_by_partial_link_text(self, link_text)
15.xpath复数定位find_elements_by_xpath(self, xpath)
16.css复数定位find_elements_by_css_selector(self, css_selector)

Selenium常用方法
单击元素.click()
写入内容.send_keys()

最后小笔记:
干完一次一定要time.sleep(1)一下,设置一个1秒的间隔!要不然会莫名其妙出问题


参考资料
使用Python实现毫秒级抢单功能 https://www.jb51.net/article/162585.htm
Selenium实现点击click() https://blog.csdn.net/lly1122334/article/details/103492202
Selenium使用send_keys()方法写中文报错的解决方法 https://blog.csdn.net/Y1013768371/article/details/90266833


发表评论