简体   繁体   中英

TypeError: object of type 'WebElement' has no len() error while looping for all img tags in a web page using selenium webdriver in Python?

Currently using selenium in python and was trying to for loop after locating element by "img" tags in whole webpage. I am trying to save all the urls and img names to my 2 arrays.

imgurl = []
imgname = []
allimgtags = browser.find_element_by_tag_name("img")

for a in len(allimgtags):
    imgurl.append(wholeimgtags.get_attribute("src"))
    imgname.append(wholeimgtags.get_attribute("alt"))

but i am getting this error in the terminal. How do i save the sub urls and names to my 2 arrays?

Traceback (most recent call last):
  File "scrpy_selenium.py", line 31, in <module>
    for a in len(wholeimgtags):
TypeError: object of type 'WebElement' has no len()

You should be using:

find_elements_by_tag_name(name)

(Notice plural)

This will return you a List of elements, then you can loop throw them.

https://www.selenium.dev/selenium/docs/api/py/webdriver_remote/selenium.webdriver.remote.webdriver.html#selenium.webdriver.remote.webdriver.WebDriver.find_elements_by_tag_name

Try to get all the img tags and loop through them.

allimgtags  = driver.find_elements_by_tag_name("img")
for img in allimgtags:
    imgurl.append(img.get_attribute("src"))
    imgname.append(img.get_attribute("alt"))

This error message...

TypeError: object of type 'WebElement' has no len()

...implies that in your program you have invoked len() method on a WebElement , where as len() method is used to get the length of the given string , array , list , tuple , dictionary , etc.


Solution

To invoke len() , instead of find_element_by_tag_name() you need to use find_elements_by_tag_name() which would return a list . So your effective code block will be:

imgurl = []
imgname = []
allimgtags = browser.find_elements_by_tag_name("img")
for imgtag in allimgtags:
    imgurl.append(imgtag.get_attribute("src"))
    imgname.append(imgtag.get_attribute("alt")) 

Alternative

As an alternative to print the src and alt attributes, you can use the following lines of code:

  • src :

     print([my_elem.get_attribute("src") for my_elem in browser.find_elements_by_tag_name("img")])
  • alt :

     print([my_elem.get_attribute("alt") for my_elem in browser.find_elements_by_tag_name("img")])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM