Python Selenium库
阅读原文时间:2023年07月09日阅读:4

Selenium库

自动化测试工具,支持多种游览器

爬虫中主要用来解决JavaScript渲染的问题

pip3 install selenium

安装游览器驱动

下载驱动地址:https://github.com/mozilla/geckodriver/releases/

基本使用

from selenium import webdriver    #游览器驱动对象
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDirverWait

browser = webdriver.Chrome()    #申明游览器对象
try:
    browser.get('https://www.baidu.com')
    input = browser.find_element_by_id('kw')    #查找id为kw的元素
    input.send_keys('Python')    #向元素发送键,敲入Python
    input.send_keys(Keys.ENTER)    #敲入回车
    wait = WebDriverWait(browser,10)    #调用等待
    wait.untill(EC.presence_of_element_located((By.ID,'content_left')))#等待ID为content_left元素加载
    print(browser.current_url)        #打印当前的url
    print(browser.get_cookies())    #打印当前cookie
    print(browser.page_source)    #page_source,打印网页源代码
finally:
    browser.close()    #关掉游览器

声明游览器对象

from selenium import webdirver    #游览器驱动对象 

browser = webdriver.Chrome()
browser = webdriver.Firefox()    #申明游览器对象
browser = webdriver.Edge()
browser = webdriver.PhantomJS()
browser = webdriver.Safari()

访问页面

from selenium import webdirver    #游览器驱动对象 

browser = webdirver.Firefox()    #申明游览器对象
browser.get('https://taobao.com')
print(browser.page_source)    ##page_source,打印网页源代码
browser.close()

查找元素

单个元素

from selenium import webdirver    #游览器驱动对象 

browser = webdirver.Firefox()    #申明游览器对象
browser.get('https://taobao.com')    

#三种方法查找
input_first = browser.find_element_by_id('q')    #查找id为q的元素
input_second = browser.find_element_by_css_selector('#q')    #使用css选择器查找
input_third = browser.find_element_by_xpath('//*[@id="q"]')    #使用xpath选择器查找

print(input_first,input_second,input_third)
browser.close
其他查找方法
  • fine_element_by_name
  • fine_element_by_xpath
  • fine_element_by_link_text
  • fine_element_by_partial_link_text
  • fine_element_by_tag_name
  • fine_element_by_class_name
  • fine_element_by_css_selector
通用查找方法
from selenium import webdriver
from selenium.webdriver.common.by import By

browser = webdriver.Firefox()
browser.get('https://taobao.com')
input_first = browser.find_element(By.ID,'q')
print(input_first)
browser.close()

多个元素

与单个元素的区别是单元数是element多元素是elements

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://taobao.com')
lis = browser.find_elements_by_css_selector('.service-bd li')
print(lis)
browser.close()


from selenium import webdriver
from selenium.webdriver.common.by import By

browser = webdriver.Firefox()
browser.get('https://taobao.com')
lis = browser.find_elements(By.CSS_SELECTOR,'.service-bd li')
print(lis)
browser.close()
其他查找方法
  • fine_elements_by_name
  • fine_elements_by_xpath
  • fine_elements_by_link_text
  • fine_elements_by_partial_link_text
  • fine_elements_by_tag_name
  • fine_elements_by_class_name
  • fine_elements_by_css_selector

元素交互操作

对获取的元素调用交互方法

from selenium import webdriver
import time

browser = webdriver.Firefox()
browser.get('https://taobao.com')
input = browser.find_element_by_id('q')    #查找id为q的元素,实际是输入框
input.send_keys('iPhone')    #输入键为iPhone
time.sleep(1)    #等待一秒
input.clear()    #清空文本框
input.send_keys('iPad')    #输入键为iPad
button = browser.find_element_by_classs_name('btn-search')        #查找name为btn-search的元素
button.click()    #跳转请求为搜索结果

交互动作

将动作附加到动作链中串行执行

from selenium import webdriver
from selenium.webdriver import ActionChains

browser = webdriver.Firefox()
url = 'http://www.runoob.com/try/try.php?filename=jqueryui-apl-droppable'
browser.get(url)
browser.switch_to.frame('iframeResult')    #切换到iframeResult元素里面
source = browser.find_element_by_css_selector('#draggable')    #查找draggable拖拽元素
target = browser.find_element_by_css_selector('#droppable')    #查找droppable被拖拽元素
actions = ActionChains(browser)    #申明动作对象
actions.drag_and_drop(source,atrget)    #进行拖拽
actions.perform()    #执行拖拽动作

执行JavaScript

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://www.zhihu.com/explore')
browser.execute_script('window.scrollTo(0,document.body.scrollHeight)')#下拉到网页最下端
browser.execute_script('alert("To Bottom")')    #提示信息To Bottom

获取元素信息

获取属性

from selenium import webdriver
from selenium.webdriver import ActionChains

browser = webdriver.Firefox()
url = 'https://www.zhihu.com/explore'
browser.get(url)
logo = browser.find_element_by_id('zh-top-link-logo')
print(logo)
print(logo.get_attribute('class'))

获取文本值

from selenium import webdriver

browser = webdriver.Firefox()
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zh-top-link-logo')
print(input.text)

获取ID、位置、标签名、大小

from selenium import webdriver

browser = webdriver.Firefox()
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zh-top-add-question')
print(input.id)
print(input.location)
print(input.tag_name)
print(input.size)

Frame

import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

browser = webdriver.Firefox()
url = 'http://www.runoob.com/try/try.php?filename=jqueryui-apl-droppable'
browser.get(url)
browser.switch_to.frame('iframeResult')    #切换到iframeResult元素里面
source = browser.find_element_by_css_selector('#draggable')
print(source)
try:
    logo = browser.fine_element_by_class_name('logo')
except:
    print('NO LOGO')
browser.switch_to.parent_frame()    #切换到其他frame
logo = browser.find_element_by_class_naem('logo')
print(logo)
print(logo.text)

等待

隐式等待

当使用隐式等待执行测试的时候,如果webDriver没有在DOM中找到元素,将继续等待,超出设定时间后这抛出找不到元素异常。当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查早DOM,默认的时间是0。

from selenium import webdriver

browser = webdriver.Firefox()
browser.implicitly_wait(10)
url = 'https://www.zhihu.com/explore'
browser.get(url)
input = browser.find_element_by_class_name('zh-top-add-question')
print(input)

显示等待

from selenium import webdriver    #游览器驱动对象
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Firefox()
url = 'https://www.taobao.com/'
browser.get(url)
wait = WebDriverWait(browser,10)
input = wait.unitil(EC.presence_of_element_located((By.ID,'q')))
button = waitunitil(EC.presence_to_be_clickable((By.CSS_SELECTOR,'.btn-search')))
print(input,button)
  • title_is 标题内容
  • title_contains 标题包含元素
  • presence_of_element_located 元素加载出,传入定位元组,如(By.ID,'p')
  • visiblility_of_element_located 元素可见,传入定位元组
  • visiblility_of 可见,传入元素对象
  • presence_of_all_element_located 所有元素加载出
  • text_to_be_present_in_element 某个元素文本包含某文字
  • text_to_be_present_in_element_value 某个元素值包含某文字
  • frame_to_be_available_and_switch_to_it frame 加载并切换
  • invisibility_of_element_located 元素不可见
  • element_to_be_clickable 元素可点击
  • staleness_of 判断一个元素是否仍在DOM,可判断页面是否已经刷新
  • element_to_be_selected 元素可选择,传元素对象
  • element_location_to_be_selected 元素可选择,传入定位元组
  • element_selection_state_to_be 传入元素对象以及状态,相等返回True,否则False
  • element_location_selected_state_to_be 传入定位元组以及状态,相等返回True,否则False
  • alert_is_present 是否出现Alert

前进后退

import time
from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://www.baidu.com/')
browser.get('https://www.taobao.com/')
browser.get('https://www.python.com/')
browser.back()
time.sleep(1)
browser.forward()
browser.close()

Cookies

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://www.zhihu.com/explore')
print(browser.get_cookies())
browser.add_cookie({'name':'name','domain':'www.zhihu.com','value':'germey'})
print(browser.get_cookies())
browser.delete_all_cookies()
print(browser.get_cookies())

选项卡管理

import time
from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://www.baidu.com/')
browser.execute_script('window.open()')
print(browser.window_handles)
browser.switch_to_window(browser.window_handles[1])
browser.get('https://www.taobao.com/')
time.sleep(1)
browser.switch_to_window(browser.window_handles[0])
browser.get('https://python.org/')

异常处理

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('https://www.baidu.com/')
browser.find_element_by_id('hello')


from selenium import webdriver
from selenium.common.exceptions import TimeoutException,NoSuchElementException
browser = webdriver.Firefox()
try:
    browser.get('https://www.baidu.com')
except TimeoutException:
    print('Time Out')
try:
    browser.find_element_by_id('hello')
except NoSuchElementException:
    print('No Elemet')
finally:
    browser.close()