【问题标题】:How to access a button inside a <div> container using selenium in python如何在 python 中使用 selenium 访问 <div> 容器内的按钮
【发布时间】:2019-05-23 21:21:59
【问题描述】:

我想访问“div”标签内的按钮,但问题是,有两个“div”标签具有相同的类名,其中一个有按钮。那么如何识别哪个有按钮并访问它。到目前为止,我试图解决,但我总是得到按钮的“无法找到元素”。

一个是:

div class="weEq5" style="will-change; width;"

另一个是:

div class="weEq5"
    button class="_35EW6"

【问题讨论】:

  • 分享您的代码和 HTML(带有标记,而不仅仅是简化文本)

标签: python-3.x selenium selenium-webdriver xpath css-selectors


【解决方案1】:

要查找包含buttondiv,首先需要选择button,然后转到父元素div

driver.find_elements_by_xpath('//button/parent::div[@class="weEq5"]')
# or
driver.find_elements_by_xpath('//button[@class="_35EW6"]/parent::div[@class="weEq5"]')

【讨论】:

  • 您似乎在使用 BeautifulSoup 语法,而 OP 正在寻找 Selenium 解决方案
  • 我的错是因为我有多个标签,@Andersson 感谢您的告知。
【解决方案2】:

要访问&lt;div&gt; 内的按钮,您可以使用Locator Strategies 中的任何一个:

  • 使用CSS_SELECTOR

    myElement = driver.findElement(By.cssSelector("div[class]:not(style)>button"))
    
  • 使用XPATH

    myElement = driver.find_element_by_xpath("//div[@class and not (@style)]/button")
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 2014-06-26
    • 2020-03-28
    相关资源
    最近更新 更多