selenium+python find_element_by_css_selector方法使用
-
1.通过类class获取
比如如下代码
<h1 class="important"> This heading is very important. </h1> <p class="important"> This paragraph is very important. </p> <p class="important warning"> This paragraph is a very important warning. </p>
在上面的代码中,两个元素的 class 都指定为 important:第一个标题( h1 元素),第二个段落(p 元素)
1> 获取class值为important的h1标签
find_element_by_css_selector(h1.importane)
2>获取所有class值为important的标签
find_element_by_css_selector(*.importane)或者find_element_by_css_selector(.importane)
3>获取class值为important warning的标签
find_element_by_css_selector(.importane.warning)
-
2.通过id获取:
首先,ID 选择器前面有一个 # 号 - 也称为棋盘号或井号
< p id="intro">This is a paragraph of introduction.</ p > |
find_element_by_css_selector(#"intro")
-
3.属性选择器:
1>.
< a title="W3School Home" href="http://w3school.com.cn">W3School</ a > |
属性中包含了title和href,
find_element_by_css_selector('a[title][href]')
2>
< a href="http://www.w3school.com.cn/about_us.asp">About W3School</ a > |
定位属性中href="http://www.w3school.com.cn/about_us.asp"的元素,
find_element_by_css_selector('a[href="http://www.w3school.com.cn/about_us.asp"]')
3>
< a href="http://www.w3school.com.cn/" title="W3School">W3School</ a > |
通过href和title来定位
find_element_by_css_selector("a[href='http://www.w3school.com.cn/about_us.asp'][title='W3School']")
4>部分属性定位
< h1 >可以应用样式:</ h1 > < img title="Figure 1" src="/i/figure-1.gif" /> < img title="Figure 2" src="/i/figure-2.gif" /> < hr /> < h1 >无法应用样式:</ h1 > < img src="/i/figure-1.gif" /> < img src="/i/figure-2.gif" /> |
定位title中包含有figure的元素:
find_element_by_css_selector("image[title~='figure']")
5>其他
[abc^="def"] 选择 abc 属性值以 "def" 开头的所有元素
[abc$="def"] 选择 abc 属性值以 "def" 结尾的所有元素
[abc*="def"] 选择 abc 属性值中包含子串 "def" 的所有元素
-
4.后代选择器
< h1 >This is a < em >important</ em > heading</ h1 > < p >This is a < em >important</ em > paragraph.</ p > |
find_element_by_css_selector("h1 em")
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
· 本地部署 DeepSeek:小白也能轻松搞定!
· 基于DeepSeek R1 满血版大模型的个人知识库,回答都源自对你专属文件的深度学习。
· 在缓慢中沉淀,在挑战中重生!2024个人总结!
· 大人,时代变了! 赶快把自有业务的本地AI“模型”训练起来!
· Tinyfox 简易教程-1:Hello World!