如何根据兄弟姐妹的文本在硒中查找元素?
How to find a element in selenium based on text from sibling?
我有一个关于 scraper selenium 的问题。
我有一堆 html,但每个 class 都有相同的名称。唯一区分一个 class 和另一个的是文本值(以红色标记)。我想为这些 class 中的每一个获取元素“显示更多”。所以我想,要获得这个元素,我必须通过范围 class _3QYUVo0T.
中的文本值以某种方式访问它
有人知道如何应对这个挑战吗?我已经和我的兄弟姐妹一起尝试了一些事情,但还是不太明白。提前致谢!
要单击 Dishes
下面的 Show more
元素,您可以使用此 XPath:
//span[text()='Dishes']/../..//span[text()='Show more']
在 Python 中使用 Selenium find_element
它将是:
driver.find_element_by_xpath("//span[text()='Dishes']/../..//span[text()='Show more']").click()
您可以以更智能和通用的方式使用它,将文本作为参数传递。
此外,您可能需要在单击元素以使其加载之前添加等待时间。
试试这个以显示更多来自 Cuisine :
//span[text()='Cuisine']/../following-sibling::div/descendant::span[text()='Show more']
菜肴:
//span[text()='Dishes']/../following-sibling::div/descendant::span[text()='Show more']
代码 1:
driver.find_element_by_xpath("//span[text()='Cuisine']/../following-sibling::div/descendant::span[text()='Show more']").click()
代码 2 :
有显式等待
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Cuisine']/../following-sibling::div/descendant::span[text()='Show more']"))).click()
进口:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
如果以上两个都不行,用JS试试:
button = driver.find_element_by_xpath("//span[text()='Cuisine']/../following-sibling::div/descendant::span[text()='Show more']")
driver.execute_script("arguments[0].click();", button)
我有一个关于 scraper selenium 的问题。
我有一堆 html,但每个 class 都有相同的名称。唯一区分一个 class 和另一个的是文本值(以红色标记)。我想为这些 class 中的每一个获取元素“显示更多”。所以我想,要获得这个元素,我必须通过范围 class _3QYUVo0T.
中的文本值以某种方式访问它有人知道如何应对这个挑战吗?我已经和我的兄弟姐妹一起尝试了一些事情,但还是不太明白。提前致谢!
要单击 Dishes
下面的 Show more
元素,您可以使用此 XPath:
//span[text()='Dishes']/../..//span[text()='Show more']
在 Python 中使用 Selenium find_element
它将是:
driver.find_element_by_xpath("//span[text()='Dishes']/../..//span[text()='Show more']").click()
您可以以更智能和通用的方式使用它,将文本作为参数传递。
此外,您可能需要在单击元素以使其加载之前添加等待时间。
试试这个以显示更多来自 Cuisine :
//span[text()='Cuisine']/../following-sibling::div/descendant::span[text()='Show more']
菜肴:
//span[text()='Dishes']/../following-sibling::div/descendant::span[text()='Show more']
代码 1:
driver.find_element_by_xpath("//span[text()='Cuisine']/../following-sibling::div/descendant::span[text()='Show more']").click()
代码 2 :
有显式等待
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Cuisine']/../following-sibling::div/descendant::span[text()='Show more']"))).click()
进口:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
如果以上两个都不行,用JS试试:
button = driver.find_element_by_xpath("//span[text()='Cuisine']/../following-sibling::div/descendant::span[text()='Show more']")
driver.execute_script("arguments[0].click();", button)