即使使用Selenium和Python有多个具有相同类名的元素,也如何通过类名标识元素 [英] How to identify an element through classname even though there are multiple elements with the same classnames using Selenium and Python

查看:93
本文介绍了即使使用Selenium和Python有多个具有相同类名的元素,也如何通过类名标识元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<div class="_2S1VP copyable-text selectable-text" data-tab="1" dir="ltr" spellcheck="true" contenteditable="true"></div>

<div class="_2S1VP copyable-text selectable-text" data-tab="3" dir="ltr" contenteditable="true"></div>

我是一个初学者,我很难区分/指定第一堂课而不是第二堂课

I'm a beginner and I've had a hard time distinguishing / specifying the first class over the second one

typing = bot.find_element_by_xpath('//div[@class = "_1Plpp"]')

这似乎不起作用,仅使用类名总是会弹出具有相同类名的不需要的第二个,我注意到它具有data-tab ="3",而另一个具有data-tab ="3"tab ="1"我将如何用data-tab ="1"来指定另一个?

this doesn't seem to work and just using the class name always brings up the unwanted second one with the same class name, I've noticed that it has data-tab="3" and the other one has data-tab="1" how would i specify the one with data-tab="1" over the other one.

推荐答案

由于两个元素的 class 属性包含相似的值,因此您将无法仅通过来区分它们class 属性,您可能需要考虑其他一些属性.

As the class attribute of both the elements contains similar values, you won't be able to distinguish them only through class attribute and you may have to consider the some other attribute(s).

要确定第一个元素,可以使用以下定位符策略:

To identify the first element you can use either of the following Locator Strategies:

  • 使用 css_selector data-tab 属性:

typing = bot.find_element_by_css_selector("div.copyable-text.selectable-text[data-tab='1']")

  • 使用 xpath data-tab 属性:

    typing = bot.find_element_by_xpath("//div[contains(@class, 'copyable-text') and @data-tab='1']")
    

  • 使用 xpath data-tab 属性:

    typing = bot.find_element_by_xpath("//div[contains(@class, 'selectable-text') and @data-tab='1']")
    

  • 这篇关于即使使用Selenium和Python有多个具有相同类名的元素,也如何通过类名标识元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆