我正在尝试定位一个元素(一个 h3
标签,只有将鼠标悬停在其上才会显示)。经过一番搜索,似乎 selenium
中的 ActionChains
是可行的方法。该代码有两个步骤: 1:找到 mouseover 对象并将鼠标悬停在其上。第2步:找到新的appread h3标签。到目前为止,步骤 1 还不错。但我在第 2 步中遇到了 Unable tolocate element:
错误。需要注意的是,出现
项是一个 iframe
对象。任何建议表示赞赏。
### Step 1: locate the mouseover object
each_username_h = review_block_html.find_element_by_xpath('.//div[starts-with(@class, "username")]')
Hover = ActionChains(driver).move_to_element(each_username_h)
Hover.perform()
### Step 2: locate new h3 tag
user_hyper_link = driver.find_element_by_xpath('.//h3[starts-with(@class, "username")]')
更新(已解决)
似乎我需要单击悬停的项目。然后我还添加了一个动态等待项目(感谢 michael satish
),确保在项目可用时找到该项目。
### Step 1: locate the mouseover object
each_username_h = review_block_html.find_element_by_xpath('.//div[starts-with(@class, "username")]')
Hover = ActionChains(driver).move_to_element(each_username_h)
Hover.perform()
### Step 1.5: click the item
each_username_h.click()
### Step 2: locate new h3 tag
user_hyper_link = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, "//a[starts-with(@href, '/members/')]")))
最佳答案
检查悬停事件后新的 h3 标签在 DOM 中可用所需的时间。
可能会在创建新的 h3 标签之前触发 find_element_by_xpath,如果是这种情况,您可能希望动态等待新的 h3 标签
关于python - 在 Python 中使用 Selenium 定位鼠标悬停元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44442291/