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

使用send_keys遇AttributeError,求新标签页打开链接解决方案

解决Selenium打开新标签页的错误问题

嘿,我来帮你搞定这个问题~先理清楚错误根源,再给你几个靠谱的解决方案:

错误原因拆解

你遇到的两个错误本质是同一个逻辑问题:

  • 'unicode' object has no attribute 'send_keys':get_attribute("href")返回的是字符串类型(Python2里是unicode,Python3里是str),而send_keys是Selenium WebElement对象专属方法,字符串自然没有这个能力。
  • list object has no attribute 'send_keys':如果不小心用了复数形式的find_elements_by_partial_link_text,得到的是WebElement列表,列表同样不能调用send_keys方法。

正确实现方案

下面给你两种常用的打开新标签页的方式,按需选择:

方法1:模拟Ctrl+点击元素(最贴近真实用户操作)

这种方式稳定性高,还原用户手动操作逻辑:

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

# 找到目标元素(注意用单数的find_element,确保拿到单个WebElement)
great_per = driver.find_element_by_partial_link_text('Know more Thoughts')
# 模拟按住Ctrl键点击元素
ActionChains(driver)\
    .key_down(Keys.CONTROL)\
    .click(great_per)\
    .key_up(Keys.CONTROL)\
    .perform()

方法2:先开空标签,再跳转目标链接(灵活控制标签页)

如果需要后续切换标签页操作,这种方式更可控:

# 找到元素并提取链接
great_per = driver.find_element_by_partial_link_text('Know more Thoughts')
person_link = great_per.get_attribute("href")

# 用JS打开新的空白标签页
driver.execute_script("window.open('');")
# 切换到新标签(window_handles是所有标签的列表,索引1代表第二个标签)
driver.switch_to.window(driver.window_handles[1])
# 在新标签加载目标链接
driver.get(person_link)

额外小提醒

  • 如果确实需要用find_elements(比如匹配多个元素),记得通过索引取单个元素,比如great_per = driver.find_elements_by_partial_link_text('Know more Thoughts')[0],避免触发列表对象的错误。
  • 切换到新标签后,若要回到原标签,可执行driver.switch_to.window(driver.window_handles[0])。

内容的提问来源于stack exchange,提问作者Mansi Mehta

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:07:09