1 import time 2 from selenium import webdriver 3 from selenium.webdriver import ActionChains 4 5 # 创建一个浏览器对象,支持各个浏览器,参数是浏览器驱动 6 web = webdriver.Chrome(executable_path='chromedriver') 7 8 # 命令浏览器打开一个网页 9 web.get(url='https://www.baidu.com') 10 """ 11 find系列: 12 除了by_id其余返回结果都是多个。 13 find_element_by_id 14 find_element_by_name 15 find_element_by_xpath 16 find_element_by_link_text 17 find_element_by_partial_link_text 18 find_element_by_tag_name 19 find_element_by_class_name 20 find_element_by_css_selector 21 """ 22 23 # 通过find系列方法,获取到指定的标签 24 search_input = web.find_element_by_id('kw') 25 26 # 为标签添加内容(值) 27 search_input.send_keys('宝宝小可爱') 28 time.sleep(2) 29 30 # 获取指定标签 31 btn = web.find_element_by_id('su') 32 33 # 对标签进行点击 34 btn.click() 35 time.sleep(2) 36 37 # 执行js代码 38 web.execute_script('window.scrollTo(0,document.body.scrollHeight)') 39 time.sleep(2) 40 # 关闭浏览器对象 41 web.close() 42 web.quit() 43 44 45 # 动作链: 46 # ActionChains是一种自动执行低级别交互的方法,例如鼠标移动,鼠标按钮操作,按键和上下文菜单交互。 47 # 这对于执行更复杂的操作非常有用,例如悬停和拖放。 48 49 # 创建一个动作链 50 action = ActionChains(web) 51 action.__init__(web) # 创建一个新的ActionChains。 52 action.click() # 单击元素。 53 action.click_and_hold() # 按住元素上的鼠标左键。 54 action.context_click() # 在元素上执行上下文单击(右键单击)。 55 action.double_click() # 双击元素。 56 57 action.drag_and_drop('source', 'target') # 按住源元素上的鼠标左键,然后移动到目标元素并释放鼠标按钮。 58 # 参数:source:鼠标按下的元素。target:要鼠标移动的元素。 59 60 action.drag_and_drop_by_offset('source', 'xoffset', 'yoffset') # 按住源元素上的鼠标左键,然后移动到目标偏移并释放鼠标按钮。 61 # 参数:source:鼠标按下的元素。xoffset:移动到的X偏移量。yoffset:移动到的Y偏移量。 62 63 action.move_by_offset('xoffset', 'yoffset') # 将鼠标移动到当前鼠标位置的偏移量。 64 # 参数:xoffset:要移动到的X偏移量,作为正整数或负整数。yoffset:要移动到的Y偏移量,作为正整数或负整数。 65 66 action.move_to_element('to_element ') # 将鼠标移动到元素的中间。to_element:要移动到的WebElement。 67 68 action.move_to_element_with_offset('to_element', 'xoffset', 'yoffset ') # 将鼠标移动指定元素的偏移量。偏移量相对于元素的左上角。 69 # 参数:to_element:要移动到的WebElement。xoffset:移动到的X偏移量。yoffset:移动到的Y偏移量。 70 71 action.pause(1) # 在几秒钟内暂停指定持续时间内的所有输入 72 action.release() # 释放元素上的鼠标按钮。 73 action.perform() # 执行所有存储的操作。 74 action.reset_actions() # 清除已存储在本地和远程端的操作。 75 76 action.key_down('value') # 仅发送按键,而不释放它。只能与修改键(Control,Alt和Shift)一起使用。 77 # 参数:value:要发送的修饰键。值在Keys类中定义。element:发送密钥的元素。如果为None,则将密钥发送到当前关注的元素。 78 79 action.key_up('value') # 释放修改键。 80 # 参数:value:要发送的修饰键。值在Keys类中定义。element:发送密钥的元素。如果为None,则将密钥发送到当前关注的元素。 81 82 action.send_keys('*keys_to_send') # 将键发送到当前聚焦元素。keys_to_send:要发送的密钥。修饰符键常量可以在“Keys”类中找到。 83 84 action.send_keys_to_element('element', '*keys_to_send') # 将键发送到元素。 85 # 参数:element:发送密钥的元素。keys_to_send:要发送的密钥。修饰符键常量可以在“Keys”类中找到。 86 87 # 举例按住ctrl+C: 88 # action.key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform() #按住ctrl,添加c再松开
代码分为两部分:
上面简单演示了一下打开百度,并进行搜索内容,滚动下屏幕,关闭浏览器。
下面是创建一个动作链,并列举动作链的方法,以及用处、参数的解释。