一.安装驱动
1.链接: http://npm.taobao.org/mirrors/selenium/. 2. 复制drive到python.exe同级目录 C:\Users\lin\AppData\Local\Programs\Python\Python39\python.exe
二.程序入门
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
click = driver.find_element_by_xpath('//*[@id="kw"]')
click.send_keys("java程序猿")
button = driver.find_element_by_xpath('//*[@id="su"]')
button.click()
三.常用方法
Driver设置
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--hide-scrollbars')
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument('blink-settings=imagesEnabled=false')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--user-agent=Mozilla/5.0 HAHA')
chrome_options.add_argument('--proxy-server=http://202.20.16.82:9527')
driver = webdriver.Chrome(options=chrome_options)
Driver方法
- driver.forward() 前进
- driver.back() 后退
- driver.add_cookie(cookie) 添加cookie
- driver.get_cookies() 获取cookie
- driver.save_screenshot("./images/baidu.png") 截屏
- source = driver.page_source 返回渲染好的页面
- driver.refresh() 页面刷新
- title = driver.title 获取标题
- driver.switch_to_window(“windowName”) 切换到内嵌的窗口
元素定位
- 1.通过id定位元素:find_element_by_id(“id_vaule”)
- 2.通过xpath定位元素:find_element_by_xpath(“xpath”)
- 3.通过class_name定位元素:find_element_by_class_name(“class_name”)
- 4.通过标签名定位元素:find_element_by_tag_name(“tag_name_vaule”)
- 5.通过link:find_element_by_link_text(“text_vaule”)
- 6.通过find_element_by_partial_link_text()
- 7.通过css定位元素:find_element_by_css_selector(“p.content”)
多元素返回list,其余用法不变
|