【问题标题】:How to use find_element_by_xpath() for svg element using Selenium for Python如何使用 Python 的 Selenium 将 find_element_by_xpath() 用于 svg 元素
【发布时间】:2020-09-26 01:26:10
【问题描述】:

我正在尝试让 Instagram 机器人在帖子被不喜欢时点赞,如果帖子已经被点赞则忽略它 我设法抓住了 div 元素并单击它,但是对于类似的检测代码,我需要 "aria-label""fill" 的属性,以便机器人指定帖子是否被喜欢,但我没有管理抓住svg 元素这样做。

这是like按钮的结构

这是我的代码:

like_button = self.driver.find_element_by_xpath(
'//*[@id="react-root"]/section/main/div/div/article/div[3]/section[1]/span[1]/button/div')
          
like_icon=like_button.find_element_by_xpath(
'//*[@id="react-root"]/section/main/div/div/article/div[3]/section[1]/span[1]/button/div/span/svg')

每当我运行它时都会发生错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="react-root"]/section/main/div/div/article/div[3]/section[1]/span[1]/button/div/span/svg"}

【问题讨论】:

  • svg[aria-label='Like'] 将是一个更容易使用的 xpath。

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


【解决方案1】:

元素是动态的WebElement,所以理想情况下,点击元素需要诱导WebDriverWaitelement_to_be_clickable(),可以使用以下Locator Strategies之一:

  • 使用CSS_SELECTOR

    like_button = WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button span > svg[aria-label='Like']"))).click()
    
  • 使用XPATH

    like_button = WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button//span//*[name()='svg' and @aria-label='Like']"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

参考文献

您可以在以下位置找到一些相关讨论:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 2016-08-31
    • 2021-03-08
    相关资源
    最近更新 更多