首页 > 解决方案 > 允许用户直接从 Python 中的 URL 中选择网页元素

问题描述

我一直在尝试找到一种方法来允许用户在 Python 中选择网页上的元素。

在下面的代码中,您可以看到我已经预定义了一个元素。我想要的是用户能够将鼠标悬停在网页上的元素上并单击它,然后将值返回给 python。非常类似于 chrome 中的元素选择器。

这可能吗?有任何想法吗

element = f"#pdp__select-size > li:nth-child({nth}) > button"

(ps 我已经导入 BeautifulSoup4 和 Selenium 来帮助抓取网页)

谢谢

金格

标签: pythonseleniumselenium-webdrivercss-selectorselement

解决方案


要将鼠标悬停在元素上并单击它,您可以使用以下代码:

from selenium.webdriver.common.action_chains import ActionChains

actions = ActionChains(driver)

element = driver.find_element_by_css_selector('f"#pdp__select-size > li:nth-child({nth}) > button"')
actions.move_to_element(element).click().perform()

推荐阅读