You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于pytest_bdd的自动化框架:无法批量点击同名用户的Add Friend按钮

问题:批量点击“添加好友”按钮失败,返回空列表

我基于pytest_bdd搭建自动化测试框架,在社交网站http://nitsanon.epizy.com/上执行自动化时多数功能正常。但登录后搜索同名用户(如Nitin kumar),想要给所有同名用户点击“Add Friend”按钮时失败——手动指定单个XPath可成功,但批量处理无法实现。

测试步骤:

  1. 登录系统
  2. 搜索目标用户(Nitin kumar)
  3. 点击“Add Friend”按钮——此步骤出现问题

相关代码片段

  • test_nitsanon.py:
@when('the user clicks on add as friend besides a user')
def sendFrndReq(browser):
    res, xp = clickBtn_multiple(browser, sendReq_addFrndBtn)
    print('\n\n\n Sent Friend Request to all users with mentioned name >>> DEBUG\n', res, xp)
  • functions.py:
# Clicks a button on every iteration
def clickBtn_multiple(browser, xpath):
    wait(3)
    res = []
    xp = []
    s = browser.find_elements(By.XPATH, xpath)
    for i in s:
        res.append(i.text)
        if xpath.is_displayed():
            a = clickBy_Xpath(browser, xpath)
            xp.append(a)
        else:
            continue
    return res, xp
  • xpaths.py:
# Send friend request
sendReq_addFrndBtn = "//div[text()='" + sendReq_name + "']/ancestor::div/div/div/div/div/div[2]/child::div[2]/div/form/div/button"
  • variables.py:
nitsanonURL = "http://nitsanon.epizy.com/"

userValue = 'nitin'
passValue = 'kumar'
sendReq_name = "Nitin kumar"

当前clickBtn_multiple函数返回空列表,请问代码哪里出错了?


问题分析与修复方案

核心错误点

  1. 错误调用元素方法:xpath.is_displayed()完全错误——xpath是字符串类型,不是WebElement对象,根本不存在is_displayed()方法,执行到这里会直接抛出异常,导致循环中断,最终返回空列表。
  2. 重复点击同一元素:循环中调用clickBy_Xpath(browser, xpath)会始终定位并点击第一个匹配到的按钮,无法实现批量点击不同用户的按钮。
  3. 等待方式不可靠:固定时长的wait(3)无法确保元素完全加载完成,容易出现元素未就绪的情况。

修复后的代码

修改functions.py中的clickBtn_multiple函数:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 批量点击按钮
def clickBtn_multiple(browser, xpath):
    res = []
    xp = []
    # 显式等待所有匹配元素加载完成
    WebDriverWait(browser, 10).until(EC.presence_of_all_elements_located((By.XPATH, xpath)))
    # 获取所有匹配的按钮元素
    buttons = browser.find_elements(By.XPATH, xpath)
    for btn in buttons:
        try:
            # 检查当前按钮是否可见且可交互
            if btn.is_displayed() and btn.is_enabled():
                res.append(btn.text)
                btn.click()
                xp.append("Success")
            else:
                xp.append("Element not interactable")
        except Exception as e:
            xp.append(f"Error: {str(e)}")
            continue
    return res, xp

额外优化建议

  • 避免硬编码XPath拼接,改成参数化函数降低全局变量依赖:
# xpaths.py
def get_add_friend_xpath(username):
    return f"//div[text()='{username}']/ancestor::div/div/div/div/div/div[2]/child::div[2]/div/form/div/button"

调用时传入用户名:

# test_nitsanon.py
@when('the user clicks on add as friend besides a user')
def sendFrndReq(browser):
    from xpaths import get_add_friend_xpath
    from variables import sendReq_name
    xpath = get_add_friend_xpath(sendReq_name)
    res, xp = clickBtn_multiple(browser, xpath)
    print('\n\n\n Sent Friend Request to all users with mentioned name >>> DEBUG\n', res, xp)

内容的提问来源于stack exchange,提问作者Nitin Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 14:05:38