简体   繁体   中英

TypeError: 'WebElement' object is not iterable

What am I missing here? the script will click like on the first profile, but fails the next one.

import time
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options

driver = Chrome()
driver.get('https://www.okcupid.com/login')
redirect = ('https://www.okcupid.com/doubletake')

username = driver.find_element_by_name('username')
password = driver.find_element_by_name("password")

username.send_keys("gmail.com")
password.send_keys("password")
#driver.find_element_by_xpath("//input[@class='login2017-actions-button']").click()
driver.find_element_by_class_name('login2017-actions-button').click()
time.sleep(5)
driver.get(redirect)

hoes = driver.find_element_by_xpath("//button[@class='cardactions-action cardactions-action--like']")

while 1:
    print('Liking')
    hoes.click()
    time.sleep(5)

But when I make these changes, it doesnt work at all:

hoes = driver.find_elements_by_xpath("//button[@class='cardactions-action cardactions-action--like']")

for matches in hoes:
    print('Liking')
    hoes.click()
    time.sleep(5)

Liking Traceback (most recent call last): File "/home/cha0zz/Desktop/scripts/okcupid.py", line 24, in <module> hoes.click() AttributeError: 'list' object has no attribute 'click'

Here

hoes = driver.find_element_by_xpath("//button[@class='cardactions-action cardactions-action--like']")

while 1:
    print('Liking')
    hoes.click()

find_element_by_xpath returns a single object. Meaning you can call click for it (if the element was found, of course) but you cannot iterate - single element is not a list and doesn't have defined __iter__ member.

In your other sample code

hoes = driver.find_elements_by_xpath("//button[@class='cardactions-action cardactions-action--like']")

for matches in hoes:
    print('Liking')
    hoes.click()
    time.sleep(5)

hoes is now a list, so you cannot click it but can iterate. Probably, you wanted to click every member of hoes , which you can do with a small fix hoes.click() => match.click() :

hoes = driver.find_elements_by_xpath("//button[@class='cardactions-action cardactions-action--like']")

for matches in hoes:
    print('Liking')
    matches.click()
    time.sleep(5)

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