【问题标题】:Same button, different text. selenium python相同的按钮,不同的文本。硒蟒
【发布时间】:2019-07-31 11:40:34
【问题描述】:

我有两种类型的按钮,具有相同的类、ID 等,但有两点不同。他们所做的动作和文字。一个有“邀请”文本,另一个有“消息”。当它是“邀请”时,我想做一些事情,而当它是“消息”时,我想做其他事情。你知道我必须使用什么吗?如果?或者我必须使用webDriverWait

这是 HTML 代码。

<button aria-label="Invite" class="button m5"> Invite </button>

<button aria-label="Message" class="button m5"> Message </button>

我尝试了类似的方法,但不起作用。你知道为什么吗?

buttons=driver.find_elements_by_class_name("button m5")
for but in (buttons):
fetch_text=but.text
if "Invite" in fetch_text:
###do somethin
else: ###do somethin

【问题讨论】:

    标签: python python-2.7 selenium selenium-webdriver selenium-chromedriver


    【解决方案1】:

    由于两个元素的className相同,你可以先使用className获取文本,然后在文本上加上if条件,然后进行相应的操作。

    例如,在你的情况下,它会像:

    fetch_element_text = driver.find_element_by_class_name("button m5").text
    
    if "Invite" in fetch_element_text:
         # Operate according to the Invite button 
    
    elif "Message" in fetch_element_text:
         # Operate according to the Message button
    

    更新答案
    根据您更新的问题,请尝试以下 xpath 以获取循环中的元素:

    buttons=driver.find_elements_by_xpath("//button[@class='button m5']")
    print(len(buttons))
    for button in buttons:
        fetch_element_text = button.text
    

    现在您可以设置与上面提到的相同的 if else 条件。

    【讨论】:

    • 谢谢!!完美运行!
    • 你能再检查一下我的代码吗?我在这种情况下更新了它,但不起作用..知道为什么吗?
    • 您遇到的错误是什么?您是否有任何理由使用循环来获取文本?
    • 如果你只需要获取一个文本,那么你不需要使用循环,因为可能有多个按钮在同一个类名和那些然后由于您使用的循环而在您的元素中更新。
    • 我正在使用循环,因为我有一个按钮列表。现在我正在运行代码,当它找到“邀请”按钮时,我等待得到错误。
    【解决方案2】:

    您可以通过xpath找到每个按钮:

    invite = driver.find_element_by_xpath("//button[@aria-label='Invite']")
    print(invite.text)   # Invite
    message = driver.find_element_by_xpath("//button[@aria-label='Message']")
    print(message.text)  # Message
    

    【讨论】:

      【解决方案3】:

      您不能使用find_elements_by_class_name 搜索多个元素。请使用xpathCssSelector

      buttons=driver.find_elements_by_xpath("//button[@class='button m5']")
      print(len(buttons))
      for button in buttons:
          fetch_text = button.text
          if "Invite" in fetch_text:
            print("Invite Button")
          else:
            print("Massage Button")
      

      buttons = driver.find_elements_by_css_selector("button.m5")
      print(len(buttons))
      for button in buttons:
         fetch_text = button.text
         if "Invite" in fetch_text:
            print("Invite Button")
         else:
            print("Massage Button")
      

      【讨论】:

        猜你喜欢
        • 2021-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-09
        • 2018-03-03
        • 1970-01-01
        相关资源
        最近更新 更多