https://deliorder-web.shoprite.com/stores/279/departments/553/products/258234
大家好,
请转到上面的 url,我的问题是,我正在尝试使用 xpath 从下拉列表“切片首选项”或“数量”中读取并选择一个随机元素,但我看不到任何选择值的方法。
当我检查开发工具时,我没有看到任何显示所有值的列表,但它显示了默认选择的一个作为 薄片
我尝试使用 Xpath 首先单击下拉菜单 //*[name()='svg'][contains(@class, 'text-sm')]
然后尝试从下拉列表中读取值,但没有用。 //*[@id='_80j8wwopf']/div[2]
我需要可以 -
的 xpath 表达式感谢这方面的帮助。
谢谢
注意 - 附件是需要帮助的地方的屏幕截图。
似乎提供的 URL 中的下拉列表不是使用标准 HTML 元素构建的。相反,它很可能是使用自定义 JavaScript 代码构建的,这意味着您无法使用简单的 XPath 表达式访问它。
在这种情况下,您可以尝试结合使用 XPath 和 JavaScript 代码来实现您的目标。这是一个示例,说明如何从“切片首选项”下拉列表中选择一个随机值:
# First, click on the dropdown to open it
driver.find_element_by_xpath("//*[name()='svg'][contains(@class, 'text-sm')]").click()
# Next, wait for the dropdown options to appear
time.sleep(1)
# Get all the dropdown options
options = driver.execute_script("return Array.from(document.querySelectorAll('#_80j8wwopf [role=\"option\"]')).map(option => option.textContent)")
# Select a random option from the list
random_option = random.choice(options)
# Click on the selected option
driver.execute_script(f"Array.from(document.querySelectorAll('#_80j8wwopf [role=\"option\"]')).find(option => option.textContent === '{random_option}').click()")
此代码首先单击“切片首选项”下拉菜单将其打开,等待一秒钟以允许出现选项,然后使用 JavaScript 检索所有下拉选项并随机选择一个。最后,它点击选中的选项进行选择。
请注意,此代码假定您在 Python 中使用 Selenium WebDriver 来自动化浏览器。如果您使用不同的工具或编程语言,则需要相应地调整代码。