selenium定位元素方法及思路补充

selenium定位元素方法

更多教程参考:

更多教程请参考:
http://selenium-python.readthedocs.io/installation.html#introduction

下列代码需要用到的库

from selenium import webdriver
import time
from lxml import etree

selenium的关闭和退出

  • driver.close() : 关闭当前浏览器页面
  • driver.quit() : 退出整个浏览器
driver_path = r"D:\Google\Chrome\Application\chromedriver.exe"
driver = webdriver.Chrome(executable_path=driver_path)
driver.get('https://www.baidu.com')
time.sleep(5)
driver.close()
# 代码运行时候时会生成一个浏览器视窗,这时再点击生成新的选项卡 ,代码运行
# 完毕的时候只会关闭第一个选项卡标签

简单例子()

在这里插入图片描述

# 这里我们通过 id 属性获取百度首页的输出框
inputTag = driver.find_element_by_id('kw')
inputTag.send_keys('python')
# 这里同样可以通过 name 属性获取
inputTag = driver.find_element_by_name('wd')
inputTag.send_keys('python')
# 通过class属性名称获取
inputTag = driver.find_element_by_class_name('s_ipt')
inputTag.send_keys('python')
# 通过Xpath语法找到标签
inputTag = driver.find_element_by_xpath('//input[@id="kw"]')
inputTag.send_keys('python')
# 通过css选择器获取
inputTag = driver.find_element_by_css_selector('.quickdelete-wrap > input')
inputTag.send_keys('python')
# 通过css选择器获取 ----- 2
inputTag = driver.find_elements_by_css_selector('.quickdelete-wrap > input')[0]
# 这里inputTag获取了多个元素,返回的是一个列表

inputTag.send_keys('python')

以上所有代码

find_element是获取第一个满足条件的元素。find_elements是获取所有满足条件的元素。

补充

如果只是想要解析网页中的数据,那么推荐把网页源代码请求下来, 然后用Lxml解析,因为Lxml底层使用的是C语言,效率更高

html = etree.HTML(driver.page_source)
exp = html.xpath()

如果是想要对元素进行一些操作,比如给一个文本框输入值,或者是点击某个按钮,那就必须使用selenium提供的查找元素的方法

发布了37 篇原创文章 · 获赞 18 · 访问量 1227

猜你喜欢

转载自blog.csdn.net/qq_41506882/article/details/104379681