How to identify an element through classname even though there are multiple elements with the same classnames using Selenium and Python

☆樱花仙子☆ 提交于 2021-01-20 07:30:11

问题


<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"]')

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.


回答1:


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:

  • Using css_selector along with data-tab attribute:

    typing = bot.find_element_by_css_selector("div.copyable-text.selectable-text[data-tab='1']")
    
  • Using xpath along with data-tab attribute:

    typing = bot.find_element_by_xpath("//div[contains(@class, 'copyable-text') and @data-tab='1']")
    
  • Using xpath along with data-tab attribute:

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


来源:https://stackoverflow.com/questions/62151967/how-to-identify-an-element-through-classname-even-though-there-are-multiple-elem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!