Reputation: 75
This is the tag containing href
.
This is the HTML of one of the links when I inspected it.
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()
but I am getting the error:
File "C:/Users/user/Desktop/sel.py", line 31, in
(session="7896348772e450d1658543632013ca4e", element="0.06572622905717385-1")>
elem.get_attribute("href").click()
AttributeError: 'str' object has no attribute 'click'
Can any one help please.
Upvotes: 0
Views: 8141
Reputation: 193108
This error message...
AttributeError: 'str' object has no attribute 'click'
...implies that you script/program have attempted to invoke click()
on a string
object.
As per the line of code:
elem.get_attribute("href").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.
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
Upvotes: 3
Reputation: 1439
The get_attribute("href")
returns the STRING of the url whichever the element is pointing to. If you want to click on the hyperlink element, just do:
for elem in elems:
print(elem)
elem.click()
driver.back() //to go back the previous page and continue over the links
On a sidenote, if you want to print the URL of the hyperlink which you are clicking, you can use your get_attribute()
method:
print(elem.get_attribute("href"))
Upvotes: 0
Reputation: 1492
The problem is the get_attribute()
method returns the value of the attribute. In this case, the attribute is href
so, it returned str
obj. Note that, the web element elem
is clickable. But, if you click on the elem
. It will take you to the next page hence, iterating over all these web elements (elems
) won't be possible as, driver will move on to next page!
Alternate way, to achieve what you are looking for is to create a list of links and, iterate over it like below:
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
This way, we are making sure to collect all the links from the web element list i.e. elems
by iterating over it. After collecting all the links and storing them in the list, we iterate over the collected list of urls.
Upvotes: 1