selenium的文档API
你用WebDriver要做的第一件事就是指定一个链接,一般我们使用get方法: fromseleniumimportwebdriver fromselenium.webdriver.common.keysimportKeys driver=webdriver.Chrome(r'D:\chrome\Google\Chrome\Application\chromedriver.exe') driver.get("https://www.baidu.com/") 你可以用下列任意方法找到它: element=driver.find_element_by_id("passwd-id") element=driver.find_element_by_name("passwd") element=driver.find_element_by_xpath("//input[@id='passwd-id']") content=driver.find_element_by_css_selector('p.content') 等等 fromseleniumimportwebdriver importtime driver=webdriver.Chrome(r'D:\chrome\Google\Chrome\Application\chromedriver.exe') driver.get("https://www.baidu.com/") inputClass=driver.find_element_by_id('kw') time.sleep(3) inputClass.send_keys("python") inputClass.clear() 这里我们举个例子就是请求百度然后输入python然后再删除掉,inputClass.clear()就是清楚搜索框内容假如前面就有内容的话可以先删除掉再输入,这里的kw就是搜索框id 然后我们需要再给我们搜索 fromseleniumimportwebdriver importtime driver=webdriver.Chrome(r'D:\chrome\Google\Chrome\Application\chromedriver.exe') driver.get("https://www.baidu.com/") inputClass=driver.find_element_by_id('kw') inputClass.send_keys("python") time.sleep(3) button=driver.find_element_by_id("su") button.click() 然后我们就可以通过page_source获取搜索后的源代码然后就是beautifulsoup等等包继续获取了 在窗口(window)和框架(frame)间移动现在的网页应用里没有页面框架或者只用一个窗口就包含了所有内容的已经很少了。WebDriver 支持在指定的窗口间移动,方法为switch_to_window: driver.switch_to_window("windowName") 这个switch_to_window用的是target标签现在所有的driver的调用都会指向这个给定的窗口,但是我们怎么知道窗口的名字是什么呢?可以看一看打开这个窗口的javascript脚本或者link链接: Clickheretoopenanewwindow 行为链ActionChains可以完成简单的交互行为,例如鼠标移动,鼠标点击事件,键盘输入,以及内容菜单交互。这对于模拟那些复杂的类似于鼠标悬停和拖拽行为很有用 不管怎样,这些动作总是一个接一个按他们被调用的顺序执行。 click(on_element=None) 点击一个元素 参数: * on_element:要点击的元素,如果是None,点击鼠标当前的位置 click_and_hold(on_element=None) 鼠标左键点击一个元素并且保持 参数: * on_element:同click()类似 double_click(on_element=None) 双击一个元素 参数: * on_element:同click()类似 drag_and_drop(source, target) 鼠标左键点击source元素,然后移动到target元素释放鼠标按键 参数: source:鼠标点击的元素 target:鼠标松开的元素 drag_and_drop_by_offset(source, xoffset,yoffset) 拖拽目标元素到指定的偏移点释放 参数: source:点击的参数 xoffset:X偏移量 * yoffset:Y偏移量 key_down(value,element=None) 只按下键盘,不释放。我们应该只对那些功能键使用(Contril,Alt,Shift) 参数: value:要发送的键,值在Keys类里有定义 element:发送的目标元素,如果是None,value会发到当前聚焦的元素上 例如,我们要按下 ctrl+c: ActionChains(driver).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).perform()key_up(value,element=None) 释放键。参考key_down的解释 move_by_offset(xoffset,yoffset) 将当前鼠标的位置进行移动 参数: xoffset:要移动的X偏移量,可以是正也可以是负 yoffset:要移动的Y偏移量,可以是正也可以是负 move_to_element(to_element) 把鼠标移到一个元素的中间 参数: * to_element:目标元素 move_to_element_with_offset(to_element,xoffset,yoffset) 鼠标移动到元素的指定位置,偏移量以元素的左上角为基准 参数: to_element:目标元素 xoffset:要移动的X偏移量 * yoffset:要移动的Y偏移量 perform() 执行所有存储的动作 release(on_element=None) 释放一个元素上的鼠标按键, 参数: * on_element:如果为None,在当前鼠标位置上释放 send_keys(*keys_to_send) 向当前的焦点元素发送键 参数: * keys_to_send:要发送的键,修饰键可以到Keys类里找到 send_keys_to_element(element,*keys_to_send) 向指定的元素发送键