selenium使用


打开/操作/关闭浏览器常用函数

# Generated by Selenium IDE

import time
import json
# from selenium import webdriver
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support import expected_conditions as EC

class get_cookie:
    def open_driver(self):
        self.driver_path = r'/Users/chengzhichang/Downloads/chromedriver'

        self.options = webdriver.ChromeOptions()
        self.options.add_argument('--no-sandbox')
        self.options.add_argument('--disable-dev-shm-usage')
        self.options.add_experimental_option('useAutomationExtension', False)
        self.options.add_experimental_option('excludeSwitches', ['enable-automation'])
        # options.add_argument('--headless') 是否隐藏浏览器页面
        # self.options..add_argument('--no-sandbox')  # 禁用沙盒 解决linux下root用户无法运行的问题
        self.options.add_argument(
            'user-agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"')  # 加入请求头
        # ip_port = '222.89.32.159:21079'
        # self.options.add_argument('--proxy-server=http://%s' % ip_port)  # selenium使用代理IP
        s = Service(executable_path=self.driver_path)
        # self.driver = webdriver.Chrome(options=self.options,executable_path=self.driver_path)
        self.driver = webdriver.Chrome(options=self.options,service=s)
        self.driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
            "source": """
                    Object.defineProperty(navigator, 'webdriver', {
                      get: () => undefined
                    })
                  """
        })

        # 隐式等待
        self.driver.implicitly_wait(20)
        # 窗口最大化
        # driver.maximize_window()
    def handle(self):
        check_url = 'https://www.xingtu.cn/'
        self.driver.get(check_url)
        self.driver.set_window_size(1439, 790)
        # driver.switch_to.frame(0
    def down_driver(self):
        # time.sleep(20)
        self.driver.quit()
        pass

if __name__ == '__main__':
    obj=get_cookie()
    # 打开浏览器
    obj.open_driver()

    # 浏览器操作
    obj.handle()

    # 关闭浏览器
    obj.down_driver()

1.无头浏览器(chrome)

selenium关闭左上方Chrome 正受到自动测试软件的控制的提示

转自 点击跳转

  • 作者:阿登20
  • 作者:阿登20
  • 链接:https://www.jianshu.com/p/f630ea488f9f
  • 来源:简书
  • 还有一些常用options的常用方法
driver_path = r'/Users/chengzhichang/Downloads/chromedriver'
check_url = 'https://k.kuaishou.com/official.html#/'
options = webdriver.ChromeOptions()
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_argument('--headless')
s = Service(executable_path=driver_path)
        # driver = webdriver.Chrome(options=options,executable_path=driver_path)
        driver = webdriver.Chrome(options=options,service=s)
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
            Object.defineProperty(navigator, 'webdriver', {
              get: () => undefined
            })
          """
 })

2.下拉框选中

1、导入 select 方法:

from selenium.webdriver.support.select import Select

2.常用

select_by_index()   #通过下标

select_by_value()  #通过value值

select_by_visible_text() #通过文本值

转自:点击跳转

3.等待方式

1.强制等待

time.sleep(10)   #强制等待十秒

2.隐式等待

driver.implicitly_wait(10)  # 隐性等待,最长等10秒

3 显示等待

locator =dirver.find_element_by_xpath('//*[@id="kw"]')

try:
    WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
except Exception as e:
        print(e)

driver: 传入WebDriver实例,即我们上例中的driver
timeout: 超时时间,等待的最长时间(同时要考虑隐性等待时间)
poll_frequency: 调用until或until_not中的方法的间隔时间,默认是0.5秒
ignored_exceptions: 忽略的异常,如果在调用until或until_not的过程中抛出这个元组中的异常,
则不中断代码,继续等待,如果抛出的是这个元组外的异常,则中断代码,抛出异常。默认只有NoSuchElementException。
转自:添加链接描述
版权声明:本文为CSDN博主「huilan_same」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/huilan_same/article/details/52544521

4.元素定位

通过id
find_element_by_id("id")

通过 name
find_element_by_name()

通过class
find_element_by_class_name()

通过标签名
find_element_by_tag_name()

通过文本
find_element_by_link_text()

通过文本模糊查询
find_element_by_partial_link_text()

通过xpath路径
find_element_by_xpath()

通过css  id是#  class是.
find_element_by_css_selector("#kw")

转自:点击跳转

5.键盘操作

简单操作

1.clear()       #清除输入框的内容

2.send_keys('内容') #在文本框内输入内容

3.click()        #点击按钮

4.submit()        #表单的提交

复杂(拖拽…)

引入包

from selenium.webdriver.common.action_chains import ActionChains

ActionChains的执行原理,当调用ActionChains方法的时候不会立即执行,而是将所有的操作暂时存储在一个队列中,当调用perform()的方法时候,队列会按照放入的先后顺序依次执行。
ActionChains所有方法

click(on_element=None)                    #单击鼠标左键
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)          #拖拽到某个坐标然后松开
move_by_offset(xoffset, yoffset)             #鼠标移动到距离当前位置(x,y)
move_to_element(to_element)               #鼠标移动到某个元素
move_to_element_with_offset(to_element, xoffset, yoffset) #将鼠标移动到距某个元素多少距离的位置
release(on_element=None)                     #在某个元素位置松开鼠标左键
perform()                                             #执行链中的所有动作

所以最后要加上

ActionChainsDriver.perform()

鼠标移动

csdn首页

        MoveElement = driver.find_element_by_xpath('//*[@id="csdn-toolbar"]/div/div/div[3]/div/div[5]/a')
        Action = ActionChains(driver)
        Action.move_to_element(MoveElement).perform()

鼠标移动点击

Element = driver.find_element_by_xpath('/html/body/div[6]/div[2]/div[2]/div[1]/div[1]/form/div/div/button')
    ActionChains(driver).click(Element).perform()

转自:点击跳转

6 .文件上传

input标签

driver.find_element_by_id('file').send_keys('文件路径')

其他标签使用pywin32调用窗口权柄使用

7. selenium找不到元素

跳转新页签后,利用切换标签页

num = driver.window_handles   #获取当前页签句柄
driver.switch_to_window(num[1])  #跳转新页签

1.定位frame的标签页中

driver.switch_to.frame(0)

2.通过元素的id 或name属性切换

driver,switch_to_frame('') #参数传frame id或者name

3、通过定位元素的方式切换

driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])

4、切换嵌套iframe

 同上 可以先切换到父iframe  然后再切换到子 iframe

5、 从子iframe 切换到父级 iframe

    driver.switch_to.parent_frame()

6、切换回主文档 ,即跳出所有iframe

driver.switch_to.default_content()   

转自:词穷墨尽

8. pywin32插件包使用

1. 安装

pip install ywin32

2. 窗口权柄查看工具WinSpy++

百度网盘链接

链接:https://pan.baidu.com/s/1BE5a3O0Yi5kXYng87lSgnQ 
提取码:aun6

3 . 函数解释

转自 :https://blog.csdn.net/seele52/article/details/17504925/

  • FindWindow(lpClassName=None, lpWindowName=None):

    • 描述:自顶层窗口(也就是桌面)开始搜索条件匹配的窗体,并返回这个窗体的句柄。不搜索子窗口、不区分大小写。找不到就返回0
      参数:
      lpClassName:字符型,是窗体的类名,这个可以在Spy++里找到。
      lpWindowName:字符型,是窗口名,也就是标题栏上你能看见的那个标题。
      说明:这个函数我们仅能用来找主窗口。
  • FindWindowEx(hwndParent=0, hwndChildAfter=0, lpszClass=None, lpszWindow=None)

    • 描述:搜索类名和窗体名匹配的窗体,并返回这个窗体的句柄。不区分大小写,找不到就返回0。
      参数:
      hwndParent:若不为0,则搜索句柄为hwndParent窗体的子窗体。
      hwndChildAfter:若不为0,则按照z-index的顺序从hwndChildAfter向后开始搜索子窗体,否则从第一个子窗体开始搜索。
      lpClassName:字符型,是窗体的类名,这个可以在Spy++里找到。
      lpWindowName:字符型,是窗口名,也就是标题栏上你能看见的那个标题。

作者:橘子一方
来源:CSDN
原文:https://blog.csdn.net/seele52/article/details/17504925
版权声明:本文为博主原创文章,转载请附上博文链接!

3. 记事本操作

1. WinSpy++工具使用

左上哪个想小风扇的标 , 直接拖到记事本窗口后返回上一层窗口,就是下图
在这里插入图片描述
右边Windows菜单栏可以选择上一层窗口和下一层窗口

2. 查找窗口句柄

# 查找窗口句柄
first_layer = win32gui.FindWindow('Notepad','新建文本文档.txt - 记事本')
print(first_layer)

3. 向记事本中写入数据

在这里插入图片描述

  1. 查找第一层窗体的第二层窗体
two_layer = win32gui.FindWindowEx(first_layer,0,'Edit',None)
print(two_layer)
  1. 向文本框中输入文本
win32gui.SendMessage(two_layer,win32con.WM_SETTEXT, None, 'hello python!')

** SendMessage( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam
)
hWnd 参数:窗口句柄。窗口可以是任何类型的屏幕对象。

Msg 参数:用于区别其他消息的常量值。(消息类型有文本、类型、大小…)

wParam 参数:通常是一个与消息有关的常量值,也可能是窗口或控件的句柄。

lParam 参数:通常是一个指向内存中数据的指针。

4. 文件下载

鼠标右键加win32点击A另存
        try:
            pdf_url = driver.find_element(By.XPATH,'/html')
            ActionContextClick = ActionChains(driver).context_click(pdf_url)
            ActionContextClick.perform()
        except Exception as e:
            print('鼠标点击整个html失败:',e)
        try:
            win32api.keybd_event(0x41, 0, 0, 0)
            win32api.keybd_event(0x41, 0, win32con.KEYEVENTF_KEYUP, 0)

        except Exception as e:
            print('Ctrl+s失败',e)

实例:

1. pdf 转换网站

https://online2pdf.com/excel2pdf

# Generated by Selenium IDE
import pytest
import time
import json

import win32con
import win32gui
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

driver = webdriver.Chrome()

driver.get("https://online2pdf.com/excel2pdf")
driver.set_window_size(1474, 824)
driver.find_element(By.CSS_SELECTOR, ".browse_button").click()

time.sleep(2)
    # self.driver.find_element(By.ID, "input_file0").send_keys("C:\\fakepath\\编程常见单词统计 - 副本.xlsx")
dialog = win32gui.FindWindow('#32770', u'打开')  # 对话框
ComboBoxEx32 = win32gui.FindWindowEx(dialog, 0, 'ComboBoxEx32', None)
ComboBox = win32gui.FindWindowEx(ComboBoxEx32, 0, 'ComboBox', None)
Edit = win32gui.FindWindowEx(ComboBox, 0, 'Edit', None)  # 上面三句依次寻找对象,直到找到输入框Edit对象的句柄
button = win32gui.FindWindowEx(dialog, 0, 'Button', "打开($O)")  # 确定按钮Button

win32gui.SendMessage(Edit, win32con.WM_SETTEXT, None, r'C:\Users\w666\Desktop\编程常见单词统计 - 副本.xlsx')  # 往输入框输入绝对地址
# win32gui.SendMessage(dialog,win32con.)
win32gui.SendMessage(dialog, win32con.WM_COMMAND, 1, button)  # 按button

9. selenium接管以打开浏览器

1.打开浏览器

  • 打开终端,进入浏览器目录(目录下有chrome.exe)
chrome.exe --remote-debugging-port=9222 --user-data-dir="D:\selenium_config"

ps:
–remote-debugging-port : 指定端口打开程序
–user-data-dir :指定新的Chrome配置文件的目录,和原来的配置文件分离开

  • 将chrome地址添加到环境变量中
  • 最后,就能直接通过selenium获取页面内容了
options = webdriver.ChromeOptions()
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-dev-shm-usage')
    options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    chrome_driver = r"D:\appdata\Reptile_demo\PY_Demo\driver\chromedriver.exe"
    driver = webdriver.Chrome(chrome_driver, chrome_options=options)
    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
           Object.defineProperty(navigator, 'webdriver', {
             get: () => undefined
           })
         """
    })
  • 试验一下
print(derver.title)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

挚友灬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值