【发布时间】:2019-03-10 14:36:27
【问题描述】:
在我的一个内部网络应用程序中,我们必须选择网页中的文本并单击选择。然后弹出一个带有更多选项的弹出窗口。这对我来说是一项重复性任务,我想将其自动化,但是像我们手动选择一个 Web 元素对我来说效果不佳。
由于我无法共享网络应用程序,所以我采取了一个所有人都可以访问的网页并尝试重新创建选择问题。
我正在尝试使用鼠标单击元素左上角来模拟手动选择,然后按 Shift,然后再次单击元素末尾。 它不工作。代码有什么问题?
预期的选择以图片的形式附上:
接下来是我的代码:
import selenium
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
print("program has started")
# Customary code starts
myDriver=selenium.webdriver.Chrome("D:\\Software\\ChromeDriver\\chromedriver.exe")
myDriver.set_page_load_timeout(60)
myDriver.maximize_window()
myDriver.implicitly_wait(30)
# Customary code ends
# opening website
myDriver.get("https://en.wikipedia.org/wiki/Animal")
time.sleep(4)
actions = ActionChains(myDriver)
element=myDriver.find_element_by_xpath("//*[@id='mw-content-text']/div/p[2]")
actions.move_to_element(element)
myDriver.switch_to_active_element()
time.sleep(5)
actions.move_by_offset(-(element.size["width"])/2, -(element.size["height"])/2)
actions.click()
ActionChains(myDriver).key_down(Keys.SHIFT)
actions.move_by_offset((element.size["width"]),(element.size["height"]))
actions.click()
# actions.context_click()
actions.perform()
# print(element.size["width"])
# print(element.size["height"])
# print(element.location["x"])
# print(element.location["y"])
# print(element.location)
print("end of action")
print("Sucessfully came to the end")
#myDriver.quit()
【问题讨论】:
-
脚本是否应该从第一次出现“Animals”到段落结尾进行选择?
-
它应该选择位于 xpath 的段落(它在代码中的命名元素)。我想将此代码扩展为仅在页面中找到某些文本时才选择元素。
-
我为您找到了解决方法,您可以使用 actions.drag_and_drop() ;我正在考虑一个可能有用的答案。
-
还有一个问题。我看到在你的 Expected selection 中,右边的图片也被选中了;但是您提供的 xpath 不包含该图片或其上方或下方的文本。这是一个错误还是选择也包括那个?
-
对不起,不应该选择图片,只需要选择xpath定义的元素。
标签: python selenium textselection