Selenium基本操作 环境准备 pip install selenium
下载对应版本的谷歌浏览器驱动chromedriver,放在Python目录的Scripts文件夹下
基本使用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver import ActionChainsfrom selenium.webdriver import ChromeOptionsfrom time import sleepfrom PIL import Imagebro = webdriver.Chrome() bro.get("https://www.baidu.com" ) kw = bro.find_element(By.ID, "kw" ) kw.send_keys("Hello" ) sleep(2 ) su = bro.find_element(By.ID, "su" ) su.click() sleep(2 ) bro.execute_script('window.scrollTo(0, document.body.scrollHeight)' ) sleep(2 ) bro.back() sleep(2 ) bro.forward() sleep(2 ) bro.quit()
如果定位的标签在iframe标签中,需要切换作用域 bro.switch_to.frame(iframe_id)
动作链
1 2 3 4 5 6 7 8 9 10 11 12 13 14 ActionChains(bro).move_to_element_with_offset(坐标).click().perform() x = 17 , y = 0 action = ActionChains(bro) action.click_and_hold(su) for i in range (5 ): action.move_by_offset(x, y).perform() sleep(0.3 ) aciton.release()
实现对某个页面中的目标元素进行截图保存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver import ActionChainsfrom selenium.webdriver import ChromeOptionsfrom time import sleepfrom PIL import Imageimport osdesktop_path = os.path.join(os.path.expanduser('~' ), 'Desktop' ) os.chdir(desktop_path) computer_scale = 1.25 options = ChromeOptions() options.add_experimental_option("excludeSwitches" , ["enable-automation" ]) options.add_argument("--disable-blink-features=AutomationControlled" ) bro = webdriver.Chrome(options=options) bro.get("https://www.baidu.com/" ) bro.save_screenshot("test.png" ) input = bro.find_element(By.ID, "kw" )location = input .location size = input .size img = Image.open ("test.png" ) img = img.crop((location["x" ] * computer_scale, location["y" ] * computer_scale, (location["x" ] + size["width" ]) * computer_scale, (location["y" ] + size["height" ]) * computer_scale)) img.save("test.png" ) bro.quit()
找到输入框输入python并回车
1 2 from selenium.webdriver.common.keys import Keysbro.find_element(By.XPATH, '//*[@id="search_input"]' ).send_keys("python" , Keys.ENTER)
切换窗口为窗口列表的最后一个
1 bro.switch_to.window(bro.window_handles[-1 ])
等待
1 2 3 4 5 6 7 8 9 from selenium.webdriver.support.wait import WebDriverWaitfrom selenium import webdriverbro = webdriver.Chrome() wait = WebDriverWait(bro, 10 ) bro.get('https://www.baidu.com' ) wait.until(lambda x: x.find_element_by_xpath('//*[@id="u1"]' ))