如何将 find_element_by_xpath() 用于 svg 元素,将 Selenium 用于 Python
How to use find_element_by_xpath() for svg element using Selenium for Python
我正在尝试让 Instagram 机器人在不喜欢 post 的情况下点赞,在已经点赞的情况下忽略它
我已经设法抓住 div 元素并单击它,但是对于类似的检测代码,我需要 "aria-label"
或 "fill"
的属性,以便机器人指定 post 是否喜欢,但我还没有设法抓住 svg
元素来这样做。
这是点赞按钮的结构
这是我的代码:
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"}
元素是动态的, so ideally, to click on the element you need to induce WebDriverWait for the element_to_be_clickable()
and you can use either of the following :
使用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
参考资料
您可以在以下位置找到一些相关讨论:
我正在尝试让 Instagram 机器人在不喜欢 post 的情况下点赞,在已经点赞的情况下忽略它
我已经设法抓住 div 元素并单击它,但是对于类似的检测代码,我需要 "aria-label"
或 "fill"
的属性,以便机器人指定 post 是否喜欢,但我还没有设法抓住 svg
元素来这样做。
这是点赞按钮的结构
这是我的代码:
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"}
元素是动态的element_to_be_clickable()
and you can use either of the following
使用
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
参考资料
您可以在以下位置找到一些相关讨论: