如何使用Selenium操作MetaMask,实现自动化交互

前置准备

  • Python 3.10.9
    • selenium 4.7.2
  • node.js 16.14.1
    • bip39

开始操作

  • node.js

首先通过 bip39 生成一个拥有 12 个助记词的新地址:

var bip39 = require('bip39');
let phrase = bip39.generateMnemonic();
console.log(phrase);

这里生成的助记词将会成为下一步自动化操作的关键

  • Python

接着开始进入正餐,首先要将 MetaMask 的插件打包成 .crx 文件,它的路径保存为变量 extension_path,它的插件ID 保存为变量 extension_id

# 导入必要的包
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

# 浏览器配置设置
extension_path = "`extension_path`"
extension_id = "`extension_id`"
opt = webdriver.ChromeOptions()
opt.add_extension(extension_path)

# 加载配置
driver = webdriver.Chrome(options=opt)

# 钱包参数 [单测试用例]
seed_phrase = "`phrase`".replace(' ', '\t\t')
password = "`psw`"
# 网络参数 [添加网络测试]
network_name = "PlatON MainNet"
network_rpc  = "https://openapi2.platon.network/rpc"
network_chainId = "210425"
network_sign = "lat"
network_scan = "https://scan.platon.network"

# 目标网站参数
website_link = "`website_link`"
# 初始化 Metamask
def init_metamask(Phrase,Password):
    print("初始化小狐狸,等待5秒")
    time.sleep(5)
    driver.switch_to.window(driver.window_handles[0])
    driver.find_element(By.XPATH,'//button[text()="开始使用"]').click()
    driver.find_element(By.XPATH,'//button[text()="不,谢谢"]').click()
    driver.find_element(By.XPATH,'//button[text()="导入钱包"]').click()

    driver.find_element(By.XPATH,'//*[@id="import-srp__srp-word-0"]').send_keys(Phrase)
    driver.find_element(By.XPATH,'//*[@id="password"]').send_keys(Password)
    driver.find_element(By.XPATH,'//*[@id="confirm-password"]').send_keys(Password)
    driver.find_element(By.XPATH,'//*[@id="create-new-vault__terms-checkbox"]').click()
    driver.find_element(By.XPATH,'//button[text()="导入"]').click()

    print("正在导入,等待5秒")
    time.sleep(5)
    driver.find_element(By.XPATH,'//button[text()="全部完成"]').click()
# 添加 PlatON 网络
def add_platon_network(name,rpc,chainId,sign,scan):
    print("开始准备添加 PlatON 网络,5秒后开始")
    time.sleep(5)
    driver.find_element(By.XPATH,'//*[@id="app-content"]/div/div[1]/div/div[2]/div/div/span').click()
    driver.find_element(By.XPATH,'//button[text()="添加网络"]').click()
    driver.find_element(By.XPATH,'//*[@id="app-content"]/div/div[3]/div/div[2]/div[2]/div/div[3]/a/h6').click()

    # 输入参数
    inputs = driver.find_elements(By.XPATH,'//input')
    inputs[1].send_keys(name)
    inputs[2].send_keys(rpc)
    inputs[3].send_keys(chainId)
    inputs[4].send_keys(sign)
    inputs[5].send_keys(scan)

    print("输入完毕,等待5秒缓冲")
    time.sleep(5)
    driver.find_element(By.XPATH,'//button[text()="保存"]').click()