Selenium 是一个自动化测试工具,可以使用它操作浏览器
声明浏览器对象 1 2 3 4 5 6 from selenuim import webdriver borwser = webdriver.Chrome() browser.get('https://www.taobao.com) print(borwser.page_source) browser.close()
查找节点 单个节点 获取淘宝首页的搜索框 可以发现 搜索框的 id 是 q, name 也是 q. 可以使用 find_element_by_name() 和 find_element_by_id() 获取 还可以根据 XPath CSS 选择器获取
1 2 3 browser.get('https://www.taobao.com' ) input_first = browser.find_element_by_id('q' ) input_second = browser.find_element_by_css_selector('#q' )
通用方法
1 2 3 from selenium.webdriver.common.by import By ele = browser.find_element(By.ID,'q' )
多个节点 1 2 3 4 find_ elements_ by _ id find_ elements_ by _n ame find_ elements_ by _ xpath ...
节点交互 1 2 3 4 5 6 7 input = browser.find_element_by_id('q' )input .send_keys('test' ) time.sleep(1 )input .clear()input .send_keys('test1' ) button =browser.find_element_by_class_name('btn-search' ) button.click()
动作链
将某个节点从位置 a 拖动到 b
1 2 3 4 5 6 7 8 9 10 11 from selenium import webdriverfrom selenium.webdriver import ActionChains browser = webdriver.Chrome() browser.get('test_url' ) browser.switch_to.frame('iframeResult' ) source = browser.find_element_by_css_selector('#draggable' ) target = browser.find_element_by_css_selector('#droppable' ) actions = ActionChains(browser) actions.drag_and_drop(source,target) actions.perform()
执行 JavaScript 1 browser.execute_script('alert("TO Bottom")' )
获取节点信息 属性 文本 1 2 logo = browser.find_element_by_id('zh -top -link -log ') print(logo.get_attribute('class ') )
切换 Frame 1 2 browser.swiich_to.frame('iframeResult' ) browser.switch_to.parent_frame()
延时等待 隐式等待 1 browser .implicitly_wait(10 )
显式等待 1 2 3 4 5 6 7 8 9 10 11 12 from selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expexted_conditions as EC browser - webdriver.Chrome() browser.get('https://www.taobao.com' ) wait = WebDriverWait(browser, 10 )input = wait_until(EC.presence_of_element_located((By.ID,'q' ))) button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'.btn-search' )))print (input ,butthon)
可见 官链
Cookies 1 2 3 browser.add_cookie ({'name' :'name' })print (browser.get_cookies() ) browser.delete_all_cookies ()
选项卡 1 2 3 browser.execute_script('window .open () ') handles = browser.window_handles browser.switch_to_window(handles [1])