基础样例

import time

from selenium import webdriver

browser=webdriver.Chrome()

browser.get("https://www.baidu.com/")

input_element=browser.find_element_by_id("kw")
input_element.send_keys("itcast")

button_element=browser.find_element_by_id("su")
button_element.click()

time.sleep(2)

url_link_element=browser.find_element_by_class_name("t")
url_link_element.click()

time.sleep(5)

browser.quit()

  • find函数
    批注 20200129 163258.jpg

一、 三个重要的API

# 1.. 定位元素  find  函数定位

element =browser.find_element_by_class_name("mnav")
print(element)

# 2..  从元素中获取文本内容

print(element.text)


# 3.. 从元素中获取属性值

print(element.get_attribute("href"))
print(element.get_attribute("class"))

二、 设置无头浏览器

#设置无头浏览器
options=webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--disable-gpu')

browser=webdriver.Chrome(chrome_options=options)

三、 模拟手机

options=webdriver.ChromeOptions()
# 模拟手机浏览器
options.add_argument('--user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 11-0 like Mac OS X)'
                     ' AppleWebkit/604.1.38 (KHTML,like Gecko) Version/11.0 Mobile/15A372 Safsri/604.1')

# 设置代理
options.add_argument('--proxy-server=代理服务器地址')
options.add_argument('--proxy-server=106.15.192.117')

browser=webdriver.Chrome(chrome_options=options)

四、 获取网页源码

browser.page_source

五、 运行js

browser.execute_script("input = document.getElementById('kw');"
                       "input.style.border='5px solid red'")

六、 三种等待方式

  1. 强制等待
time.sleep(2)
  1. 隐形等待
    让页面加载时间为5秒,如果加载完成就继续执行,ajax加载可能不行
browser.implicitly_wait(5)
  1. 检查
  • 手动检查
t = time.time()
timeout = 20

while True:
    try:
        time.sleep(0.5)
        url_link_element = browser.find_element_by_class_name("t")
        break
    except:
        if time.time() - t > timeout:
            break
  • API
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


# 1.创建等待对象
wait=WebDriverWait(browser,20,0.2)

# 2.  presence_of_element_located  判断元素是否存在
url_link_element=wait.until(EC.presence_of_element_located((By.CLASS_NAME,"t")))
url_link_element.click()

七、 窗口切换

# 获取窗口列表
print(browser.window_handles)
print(browser.current_window_handle)
print("切换前:"+browser.title)

# 切换到第二个窗口
browser.switch_to.window(browser.window_handles[1])
print(browser.current_window_handle)
print("切换后:"+browser.title)

八、 iframe切换

print(browser.page_source)
print("*"*100)

# 获取 iframe 元素对象
iframe_element=browser.find_element_by_id("iframe2")

# 切换 iframe
browser.switch_to.frame(iframe_element)
print(browser.page_source)
print("*"*100)

# 切换回原来的主页面
browser.switch_to.default_content()
print(browser.page_source)

九、 截取验证码图片,点击验证码

# 截取验证码图片
# 1> 截取全屏图片
full_image_data = browser.get_screenshot_as_png()

# 2> 获取图片元素对象
login_img_element = wait.until(EC.visibility_of_element_located((By.ID, 'J-loginImg')))
print(login_img_element.location)
print(login_img_element.size)
scale = 1.25
x1 = login_img_element.location["x"] * scale
y1 = login_img_element.location["y"] * scale
x2 = x1 + login_img_element.size["width"] * scale
y2 = y1 + login_img_element.size["height"] * scale
cut_info = (x1, y1, x2, y2)

# 3> 根据位置信息从全屏图片中截取验证码图片
# 把全屏图片数据转化为图片操作对象
full_img = Image.open(BytesIO(full_image_data))

# 4> 截取图片
cut_img = full_img.crop(cut_info)
full_img.save('full.png')
cut_img.save('cut_img.png')

#  发送打码平台
result = [1, 6]
# 定义8个坐标点
positions = [
    (50, 100),
    (150, 100),
    (250, 100),
    (300, 100),
    (50, 200),
    (150, 200),
    (250, 200),
    (300, 200)
]

# 模拟点击坐标
for num in result:
    position = positions[int(num) - 1]
    # 动作链对象
    action = ActionChains(browser)
    action.move_to_element_with_offset(login_img_element, position[0] / scale, position[1] / scale).click().perform()
time.sleep(10)

ActionChains

from selenium.webdriver import ActionChains

options = webdriver.ChromeOptions()
browser = webdriver.Chrome(chrome_options=options,
                           executable_path='C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe')
actions = ActionChains(browser)
  • 方法
click(on_element=None) ——单击鼠标左键
move_to_element(to_element) ——鼠标移动到某个元素
send_keys_to_element(element, *keys_to_send) ——发送某个键到指定元素
perform() ——执行链中的所有动作
------------------------------------------------------------------
click_and_hold(on_element=None) ——点击鼠标左键,不松开
context_click(on_element=None) ——点击鼠标右键
double_click(on_element=None) ——双击鼠标左键
drag_and_drop(source, target) ——拖拽到某个元素然后松开
drag_and_drop_by_offset(source, xoffset, yoffset) ——拖拽到某个坐标然后松开
key_down(value, element=None) ——按下某个键盘上的键
key_up(value, element=None) ——松开某个键
move_by_offset(xoffset, yoffset) ——鼠标从当前位置移动到某个坐标
move_to_element_with_offset(to_element, xoffset, yoffset) ——移动到距某个元素(左上角坐标)多少距离的位置
release(on_element=None) ——在某个元素位置松开鼠标左键
send_keys(*keys_to_send) ——发送某个键到当前焦点的元素

selenium获取cookie,使用cookie

  • 获取cookie,browser.get_cookies()
  • 添加cookies,browser.add_cookie(cookie)
cookies = browser.get_cookies()
for cookie in cookies:
    browser.add_cookie(cookie)
# 另一种方式
browser.get_cookie(name='JSESSIONID').get('value')
  • 将browser.get_cookies()获取到的cookies转为dict
cookies = browser.get_cookies()
cookie_dict = {}
for cookie in cookies:
    cookie_dict[cookie['name']] = cookie['value']

print(cookie_dict)

hhhhh