使用Python Selenium选择一个元素(文本)

时间:2018-10-05 06:37:21

标签: python selenium textselection

在我的一个内部Web应用程序中,我们必须在网页中选择文本,然后单击所选内容。然后会弹出一个带有更多选项的弹出窗口。对我来说,这是一项重复性的任务,我想使其自动化,但是像我们手动进行的那样选择一个Web元素对我来说效果不佳。

由于我无法共享该Web应用程序,因此我采取了一个所有人均可访问的网页,并尝试重新创建选择问题。

我试图通过使用鼠标单击元素左上角,然后按 Shift ,然后再次单击元素末尾来模拟手动选择。 没用代码有什么问题?

期望的选择随图片附上:

Expected selection is attached as a picture

接下来是我的代码:

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()

1 个答案:

答案 0 :(得分:0)

 # calling a action method as A
        a=A(self.driver)
        # Click on text box and enter some text
        self.driver.find_element_by_xpath("/html/body/div[3]/div[3]/div/div/div/div/div[1]/main/div/form/div[1]/div[2]/div/div/div/div[1]/section/div[1]/div/div/div/div[2]/div/div/div/div/div/div").send_keys("amar")
        time.sleep(2)
        # performing control action
        a.key_down(K.CONTROL).send_keys("a").perform()
        time.sleep(2)
        # selecting the text
        a.key_down(K.CONTROL).send_keys("c").perform()
        time.sleep(5)
        #click on bold and appl
        self.driver.find_element_by_xpath("/html/body/div[3]/div[3]/div/div/div/div/div[1]/main/div/form/div[1]/div[2]/div/div/div/div[1]/section/div[1]/div/div/div/div[1]/div[1]/div[1]").click()
        time.sleep(5)