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

Selenium WebDriver find_element方法“位置参数不能在关键字参数后”问题解决

问题解决:Pylance提示"Positional argument cannot appear after keyword arguments"

错误原因

你调用driver.find_element(by=By.CLASS_NAME, "information")时违反了Python语法规则:位置参数不能出现在关键字参数之后。这里by=By.CLASS_NAME是关键字参数,而"information"是位置参数,两者混用触发了Pylance的语法报错。

正确写法

Selenium 4的find_element方法支持两种合法调用方式:

方式1:纯位置参数(推荐写法)

直接传入定位策略和定位值,无需指定关键字:

element = driver.find_element(By.CLASS_NAME, "information")

方式2:纯关键字参数

同时指定by和value两个关键字参数:

element = driver.find_element(by=By.CLASS_NAME, value="information")

修正后的完整Python代码

#find web elements in snappit.html file
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

def test_locators():
    driver=webdriver.Chrome()
    driver.implicitly_wait(0.5)
    driver.get("file:///F:/Ahmad/python_test/selenium_test/snappit.html")
    # 使用推荐的位置参数写法
    element = driver.find_element(By.CLASS_NAME, "information")
    # 可添加代码验证元素定位结果
    print(element.get_attribute("value"))
    driver.quit()

test_locators()

补充说明

你的HTML代码中class="information"的元素是合法存在的,定位逻辑本身无问题,只需修正find_element的参数传递方式即可解决报错。

内容的提问来源于stack exchange,提问作者Ahmad Hafez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:59:59