最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python實(shí)現(xiàn)自動(dòng)化控制瀏覽器的操作指南

 更新時(shí)間:2025年07月01日 09:44:25   作者:qi諾  
這篇文章主要為大家詳細(xì)介紹了如何使用Python中的selenium庫進(jìn)行自動(dòng)化測試的關(guān)鍵操作,包括瀏覽器控制,元素交互,鼠標(biāo)和鍵盤操作等內(nèi)容,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

一、控制瀏覽器相關(guān)操作

1、控制瀏覽器窗口大小

全屏顯示maximize_window()

from selenium import webdriver

driver = webdriver.Chrome()
driver.implicitly_wait(3)
#全屏顯示
driver.maximize_window()

指定瀏覽器大小set_window_size(w, h)

#指定瀏覽器大小
driver.set_window_size(600,400)

2、控制瀏覽器前進(jìn)forward()和后退back()

#前進(jìn)
driver.forward()
#后退
driver.back()

3、刷新refresh()

#刷新頁面
driver.refresh()

4、窗口截屏

img_dir = "C:\\測試\\img.png"
driver.save_screenshot(img_dir)

二、webdriver常用方法

序號(hào)方法描述
1clear()清除
2send_keys(“value”)輸入內(nèi)容
3click()點(diǎn)擊事件
4submit()提交
5size元素尺寸
6text元素文本
7get_attribute()獲取屬性
8is_displayed()查看該元素是否用戶可見

三、鼠標(biāo)操作

序號(hào)方法描述
1click()鼠標(biāo)點(diǎn)擊事件
2move_to_element()鼠標(biāo)懸停效果
3context_click()鼠標(biāo)右擊事件
4double_click()鼠標(biāo)雙擊事件
5drag_and_drop()鼠標(biāo)拖動(dòng)事件

1、單擊事件

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

driver = webdriver.Chrome()
driver.implicitly_wait(3)
driver.get("https://www.baidu.com")
driver.find_element(By.ID,"kw").send_keys("單擊事件")
element = driver.find_element(By.CSS_SELECTOR,'#su')
ActionChains(driver).click(element).perform()

2、鼠標(biāo)懸停

#鼠標(biāo)懸停
ActionChains(driver).move_to_element(element).perform()

3、鼠標(biāo)右擊事件

#鼠標(biāo)右擊擊事件
ActionChains(driver).context_click(element).perform()

4、鼠標(biāo)雙擊事件

#鼠標(biāo)雙擊事件
ActionChains(driver).double_click(element).perform()

5、鼠標(biāo)拖動(dòng)事件

#鼠標(biāo)拖動(dòng)事件
tag = driver.find_element(By.CSS_SELECTOR,"#div1")
ActionChains(driver).drag_and_drop(element,tag).perform()

四、鍵盤相關(guān)操作

序號(hào)方法描述
1send_keys(Keys.BACK_SPACE)刪除鍵(BackSpace)
2send_keys(Keys.SPACE)空格鍵(Space)
3send_keys(Keys.TAB)Tab 鍵
4send_keys(Keys.ESCAPE)ESC 鍵
5send_keys(Keys.ENTER)Enter 回車鍵
6send_keys(Keys.CONTROL,“a”)Ctrl+a | Ctrl+c | Ctrl+x | Ctrl+v
7send_keys(Keys.F1)F1~F12

以Enter回車鍵為例演示

from selenium import webdriver
from selenium.webdriver.common.by import By
# 引入Keys模塊
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
#鍵盤按鍵操作
element=driver.find_element(By.ID,"kw")
element.send_keys("Enter回車事件")
element.send_keys(Keys.ENTER)

五、顯示等待和隱式等待

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome()
#隱式等待
driver.implicitly_wait(3)
driver.get("https://www.baidu.com")
#顯示等待
WebDriverWait(driver,5,1).until(expected_conditions.visibility_of_element_located(By.ID,"kw"))

六、方法補(bǔ)充

Python 自動(dòng)化控制Chrome瀏覽器 DrissionPage

實(shí)現(xiàn)代碼

# !/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: JHC000abc@gmail.com
@file: demo.py
@time: 2024/1/30 10:46
@desc:

"""
import json
import os
import time
import datetime
import random
import traceback

from DrissionPage import WebPage, ChromiumOptions, SessionOptions


class DrissionPageDemo(object):
    """

    """

    def __init__(self):
        """

        """

    def get_page(self, ua=None, incognito=False, time_out=60, headless=False, cookies=None):
        """

        :param ua:
        :param incognito:
        :return:
        """
        self.page = None
        co = ChromiumOptions()
        so = SessionOptions()
        if cookies:
            so.set_cookies(cookies)
        if ua:
            co.set_user_agent(user_agent=ua)
        co.incognito(incognito)
        co.set_argument('--window-size', '800,600')
        co.auto_port(True)
        co.headless(headless)
        co.ignore_certificate_errors(True)
        co.mute(True)
        co.set_timeouts(page_load=time_out)

        self.page = WebPage(driver_or_options=co, session_or_options=so)

        return self.page

    def save_result(self, html):
        """

        :param html:
        :return:
        """
        os.makedirs("result", exist_ok=True)
        file = "result/result_{}.html".format(
            datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S"))

        with open(file, "w", encoding="utf-8")as fp:
            fp.write(html)

    def read_file(self, file):
        """

        :param file:
        :return:
        """
        res = []
        with open(file, "r", encoding="utf-8")as fp:
            for i in fp:
                res.append(i.strip())
        return res

    def read_json_file(self, file):
        """

        :param file:
        :return:
        """
        with open(file, "r", encoding="utf-8")as fp:
            return json.loads(fp.read())

    def check_load_over(self):
        """

        :return:
        """

    def process(self):
        """

        :return:
        """
        url_list = self.read_file("url.list")
        ua_list = self.read_file("ua.list")
        cookie_list = self.read_file("cookie.list")
        settings = self.read_json_file("settings.json")
        time_out = settings["time_out"]
        wait = settings["wait"]
        save = settings["save"]
        incognito = settings["incognito"]
        headless = settings["headless"]
        while True:
            try:
                if ua_list:
                    ua = random.choices(ua_list)[0]
                else:
                    ua = None
                if cookie_list:
                    cookie = random.choices(cookie_list)
                else:
                    cookie = None

                self.get_page(ua, incognito, time_out, headless, cookie)

                url = random.choices(url_list)[0]
                print(f"url : {url}")

                self.page.get(url, retry=3, interval=3)
                if save:
                    html = self.page.html
                    self.save_result(html)

                self.page.quit()

                if len(wait) == 1:
                    _sleep = wait[0]
                else:
                    _sleep = random.randint(wait[0], wait[1])

                while _sleep >= 0:
                    print(f"SLEEP : {_sleep}", end='\r')
                    time.sleep(1)
                    _sleep -= 1
            except BaseException:
                print(traceback.print_exc())
                os.system("taskkill /F /IM chrome.exe")


if __name__ == '__main__':
    dp = DrissionPageDemo()
    dp.process()

到此這篇關(guān)于python實(shí)現(xiàn)自動(dòng)化控制瀏覽器的操作指南的文章就介紹到這了,更多相關(guān)python控制瀏覽器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • TensorFlow繪制loss/accuracy曲線的實(shí)例

    TensorFlow繪制loss/accuracy曲線的實(shí)例

    今天小編就為大家分享一篇TensorFlow繪制loss/accuracy曲線的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • python 輸入字符串生成所有有效的IP地址(LeetCode 93號(hào)題)

    python 輸入字符串生成所有有效的IP地址(LeetCode 93號(hào)題)

    這篇文章主要介紹了python 生成所有有效的IP地址的方法,幫助大家解答題目,學(xué)習(xí)python,感興趣的朋友可以了解下
    2020-10-10
  • 從源碼到Docker全方位解析Python項(xiàng)目打包完整指南

    從源碼到Docker全方位解析Python項(xiàng)目打包完整指南

    在實(shí)際開發(fā)中,將Python項(xiàng)目打包成可部署的格式是一個(gè)至關(guān)重要的環(huán)節(jié),本文將全面介紹Python項(xiàng)目的各種打包方式,從基礎(chǔ)的分發(fā)打包到現(xiàn)代化的Docker容器化部署,希望對(duì)大家有所幫助
    2025-11-11
  • Python動(dòng)態(tài)加載模塊的3種方法

    Python動(dòng)態(tài)加載模塊的3種方法

    這篇文章主要介紹了Python 動(dòng)態(tài)加載模塊的3種方法,本文分別使用使用系統(tǒng)函數(shù)__import_()、使用imp 模塊、使用exec三種方法實(shí)現(xiàn),需要的朋友可以參考下
    2014-11-11
  • Python hashlib模塊的使用示例

    Python hashlib模塊的使用示例

    這篇文章主要介紹了Python hashlib模塊的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下
    2020-10-10
  • Python基于Tensor FLow的圖像處理操作詳解

    Python基于Tensor FLow的圖像處理操作詳解

    這篇文章主要介紹了Python基于Tensor FLow的圖像處理操作,結(jié)合實(shí)例形式分析了Python基于Tensor FLow操作圖像解碼、縮放、剪切、翻轉(zhuǎn)、調(diào)整對(duì)比度、明度、飽和度等相關(guān)操作技巧,需要的朋友可以參考下
    2020-01-01
  • Python中隱藏的五種實(shí)用技巧分享

    Python中隱藏的五種實(shí)用技巧分享

    這篇文章主要和大家分享五個(gè)Python中隱藏的實(shí)用技巧,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Python有一定的幫助,感興趣的小伙伴可以學(xué)習(xí)一下
    2022-05-05
  • Python 對(duì)象序列化與反序列化之pickle json詳細(xì)解析

    Python 對(duì)象序列化與反序列化之pickle json詳細(xì)解析

    我們知道在Python中,一切皆為對(duì)象,實(shí)例是對(duì)象,類是對(duì)象,元類也是對(duì)象。本文正是要聊聊如何將這些對(duì)象有效地保存起來,以供后續(xù)使用
    2021-09-09
  • MATLAB中print函數(shù)使用示例詳解

    MATLAB中print函數(shù)使用示例詳解

    print函數(shù)的功能是打印圖窗或保存為特定文件格式,這篇文章主要介紹了MATLAB中print函數(shù)使用,需要的朋友可以參考下
    2023-03-03
  • Python使用wxPython實(shí)現(xiàn)計(jì)算器

    Python使用wxPython實(shí)現(xiàn)計(jì)算器

    這篇文章主要為大家詳細(xì)介紹了Python使用wxPython實(shí)現(xiàn)計(jì)算器,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-01-01

最新評(píng)論

武冈市| 施秉县| 宁明县| 桐城市| 游戏| 安平县| 民丰县| 临桂县| 周宁县| 杭锦后旗| 车致| 娄底市| 三河市| 南投市| 广宗县| 微博| 微山县| 乌拉特前旗| 察雅县| 亳州市| 德化县| 和林格尔县| 山阴县| 缙云县| 金沙县| 达州市| 佛山市| 东阿县| 论坛| 东明县| 开原市| 崇义县| 玉田县| 苏尼特左旗| 漳平市| 攀枝花市| 石台县| 兴文县| 曲阜市| 商洛市| 宜丰县|