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

Selenium报错InvalidArgumentException:'using'必须是字符串求助

Selenium Instagram登录脚本报错解决:invalid argument: 'using' must be a string

错误原因

你出错的代码行Weblog = driver.find_element({By.CSS_SELECTOR: {'name': 'username'}})完全不符合Selenium的API调用规范。find_element方法需要接收定位方式和定位值两个参数(或对应的关键字参数),而你传入了一个嵌套字典,导致Selenium无法识别合法的定位方式,因此抛出invalid argument: 'using' must be a string错误。

修正后的代码

方式1:使用NAME定位(更直接)

根据用户名输入框的name属性定位,是最直接的方式:

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

webpage = r"https://www.instagram.com/"
login = '你的账号'

driver = webdriver.Chrome()
driver.get(webpage)

# 处理可能的Cookie同意弹窗(可选,根据页面实际情况)
try:
    cookie_accept_btn = driver.find_element(By.XPATH, "//button[contains(text(), '同意')]")
    cookie_accept_btn.click()
except:
    pass

# 正确定位用户名输入框
Weblog = driver.find_element(By.NAME, "username")
Weblog.send_keys(login)

方式2:使用CSS_SELECTOR定位

如果坚持用CSS选择器,正确的写法是通过属性选择器匹配name属性:

Weblog = driver.find_element(By.CSS_SELECTOR, "[name='username']")

补充说明

  • Instagram页面可能会有动态加载或反爬机制,如果定位元素时出现超时,建议添加显式等待:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 显式等待用户名输入框出现,最多等待10秒
Weblog = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.NAME, "username"))
)
Weblog.send_keys(login)

内容的提问来源于stack exchange,提问作者Абсамат Зайналбеков

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:12:09