AttributeError: 'str' 对象在尝试遍历 href 并通过 Selenium 和 Python 单击它们时没有属性 'click' [英] AttributeError: 'str' object has no attribute 'click' while trying to loop through the hrefs and click them through Selenium and Python

查看:44
本文介绍了AttributeError: 'str' 对象在尝试遍历 href 并通过 Selenium 和 Python 单击它们时没有属性 'click'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是包含href的标签.这是我检查其中一个链接的 HTML.

我用来循环链接的代码是:

The code I used to for looping through the links is:

elems = driver.find_elements_by_xpath("//a[@href]")
for elem in elems:
    print(elem)
    elem.get_attribute("href").click()

但我收到错误:

文件C:/Users/user/Desktop/sel.py",第 31 行,

File "C:/Users/user/Desktop/sel.py", line 31, in

(session="7896348772e450d1658543632013ca4e",element="0.06572622905717385-1")>

(session="7896348772e450d1658543632013ca4e", element="0.06572622905717385-1")>

elem.get_attribute("href").click()

AttributeError: 'str' 对象没有属性 'click'

AttributeError: 'str' object has no attribute 'click'

有人可以帮忙吗.

推荐答案

此错误信息...

AttributeError: 'str' object has no attribute 'click'

...暗示您的脚本/程序已尝试在 string 对象上调用 click().

...implies that you script/program have attempted to invoke click() on a string object.

根据代码行:

elem.get_attribute("href").click()

您已经从 List elems 中提取了第一个元素的 href 属性.get_attribute() 方法返回一个字符串.String 数据类型不能调用 click() 方法.因此您会看到错误.

You have extracted the href attribute of the first element from the List elems. get_attribute() method returns a string. String data types can't invoke click() method. Hence you see the error.

现在,在您提取 href 属性并希望打开 Links 的所有可能性时,一个可行的解决方案是打开 (href) 链接相邻的 TABs 如下:

Now, in all possibilities as you are extracting the href attributes and you want to open the Links and a viable solution will be to open the (href) links in the adjacent TABs as follows:

elems = driver.find_elements_by_xpath("//a[@href]")
for elem in elems:
    print(elem)
    my_href = elem.get_attribute("href")
    driver.execute_script("window.open('" + my_href +"');")
    # perform your tasks in the new window and switch back to the parent windown for the remaining hrefs

这篇关于AttributeError: 'str' 对象在尝试遍历 href 并通过 Selenium 和 Python 单击它们时没有属性 'click'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆