【问题标题】:AttributeError: 'str' object has no attribute 'click' while trying to loop through the hrefs and click them through Selenium and PythonAttributeError: 'str' 对象在尝试遍历 href 并通过 Selenium 和 Python 单击它们时没有属性 'click'
【发布时间】:2018-12-05 23:08:33
【问题描述】:

This is the tag containing hrefThis is the HTML of one of the links when I inspected it.

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

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 行,在

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

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

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

谁能帮帮我。

【问题讨论】:

  • 可以分享相关的html吗?
  • @prany 你想要完整的源代码吗?
  • @vijayMV - 不是整个源代码,而是与您的问题相关的源代码
  • @prany 我在帖子中附上了其中一个链接 html 的图片。
  • 我在你的 html 中看不到任何 href

标签: python python-3.x selenium selenium-webdriver webdriver


【解决方案1】:

此错误消息...

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

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

出了什么问题

按照代码行:

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

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

解决方案

现在,在您提取href 属性并且想要打开链接 的所有可能性中,可行的解决方案是打开相邻TABs 中的(href)链接如下:

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

【讨论】:

  • +1 用于新窗口技巧。 OP 可能想要从docs 签出window_handlesswitch_to
【解决方案2】:

问题是get_attribute() 方法返回属性的值。在这种情况下,属性是hrefso,它返回strobj。请注意,网络元素elem 是可点击的。但是,如果您点击elem。它将带您到下一页,因此无法遍历所有这些 Web 元素 (elems),因为驱动程序将转到下一页!

另一种方法,实现您正在寻找的内容是创建一个链接列表,并像下面那样对其进行迭代:

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

for link in links:
    driver.get(link)
    # do you stuff

通过这种方式,我们确保通过迭代从网络元素列表(即elems)中收集所有链接。在收集所有链接并将它们存储在列表中之后,我们遍历收集的 url 列表。

【讨论】:

  • 很好地指出了循环的问题。如果用户必须对每个链接执行不同的操作,他将不得不添加更多的条件。
  • @Shivam Mishra 如果我想从每个链接中提取一些信息,我应该在现有代码中添加什么?
  • 感谢 Shivam Mishra。 @vijayMV 检查DebanjanB's Answer below
  • @vijayMV 您想在每个链接中测试什么?您可以在答案中使用任何方法。我想说的是,如果您使用此答案中的方法,则必须检查驱动程序当前所在的页面,即如果链接==链接1,则执行 test1 等等。那是因为我假设您必须对不同的链接执行不同的操作。
【解决方案3】:

get_attribute("href") 返回该元素指向的 url 的字符串。如果你想点击超链接元素,只需:

for elem in elems:
    print(elem)
    elem.click()
    driver.back() //to go back the previous page and continue over the links

在旁注中,如果你想打印你点击的超链接的 URL,你可以使用你的 get_attribute() 方法:

print(elem.get_attribute("href"))

【讨论】:

    猜你喜欢
    • 2022-10-14
    • 2022-12-05
    • 2018-07-20
    • 1970-01-01
    • 2022-01-06
    • 2018-12-20
    • 2012-06-28
    • 1970-01-01
    相关资源
    最近更新 更多