AttributeError:'str'对象在尝试遍历hrefs并通过Selenium和Python单击它们时没有属性'click'

问题描述 投票:0回答:3

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

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

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

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

请任何人帮忙。

python python-3.x selenium selenium-webdriver webdriver
3个回答
3
投票

此错误消息...

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

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

什么地方出了错

根据代码行:

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

您已从List elems中提取了第一个元素的href属性。 get_attribute()方法返回一个字符串。字符串数据类型无法调用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

0
投票

问题是get_attribute()方法返回属性的值。在这种情况下,属性是hrefso,它返回str obj。请注意,web元素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

这样,我们确保通过迭代来收集来自web元素列表的所有链接,即elems。在收集所有链接并将它们存储在列表中之后,我们迭代收集的URL列表。


0
投票

get_attribute("href")返回url的STRING,无论元素指向哪个。如果要单击超链接元素,只需执行以下操作:

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"))
© www.soinside.com 2019 - 2024. All rights reserved.