一、搭建环境
1、下载python,并安装配置环境变量
下载地址:https://www.python.org/downloads/
2、下载pychram,并把python添加到pycharm
下载地址:https://www.jetbrains.com/pycharm/download/
3、安装selenium
a、直接在pycharm上安装selenium
b、或者在电脑cmd安装,输入: pip install selenium
4、下载chrmoe插件,并把它放到python的根目录下
a、查看谷歌浏览器的版本号
b、插件下载地址:http://chromedriver.storage.googleapis.com/index.html
c、把插件放在python根目录下
5、检查是否搭建成功
#!user/bin/env python
#_*_coding:utf-8_*_
import time
from selenium import webdriver
# 选择谷歌浏览器
driver = webdriver.Chrome()
# 输入网址
driver.get("https://www.baidu.com/")
time.sleep(3)
#元素定位输入框,并输入搜索条件
driver.find_element_by_id("kw").send_keys("python")
time.sleep(3)
#定位按钮"百度一下"
driver.find_element_by_id("su").click()
time.sleep(3)
# 关闭网址
driver.quit()
二、定位元素
查找元素,可以通过以下方式查找
a、find_element_by_id() #通过id查找![在这里插入图片描述](https://img-blog.csdnimg.cn/20210326203202208.png)
b、find_element_name() #通过name查找
c、find_element_class_name #通过class name查找
d、find_element_by_tag_name() #通过 tag name查找
e、find_element_by_css_selector() #通过CSS查找
f、find_element_by_xpath() #通过xpath查找
g、find_element_by_partial_link_text() #通过partial link text查找
h、find_element_by_link_text() #通过link text查找