简体   繁体   中英

Appending list from a for loop

I am trying to populate a list with links collected from a web page. The list is coming up with an unexpected result. What is wrong with the code I am using?

def get_contact_id(self):
    wd = self.app.wd
    elements = wd.find_elements_by_xpath("//a[contains(@href, 'edit.php?id')]")
    print(elements)
    links = []
    for i in elements:
        link = i.get_attribute('href')
        links.append(link)
        print(links)

I expect to get:

links = ['//192.168.1.22:8080/addressbook/edit.php?id=9','//192.168.1.22:8080/addressbook/edit.php?id=11','//192.168.1.22:8080/addressbook/edit.php?id=13','//192.168.1.22:8080/addressbook/edit.php?id=10','//192.168.1.22:8080/addressbook/edit.php?id=14']

Instead I am getting:

links = ['//192.168.1.22:8080/addressbook/edit.php?id=9']
['//192.168.1.22:8080/addressbook/edit.php?id=9','//192.168.1.22:8080/addressbook/edit.php?id=10']
['//192.168.1.22:8080/addressbook/edit.php?id=9', '//192.168.1.22:8080/addressbook/edit.php?id=10', '//192.168.1.22:8080/addressbook/edit.php?id=11']
['//192.168.1.22:8080/addressbook/edit.php?id=9', '//192.168.1.22:8080/addressbook/edit.php?id=10', '//192.168.1.22:8080/addressbook/edit.php?id=11', '//192.168.1.22:8080/addressbook/edit.php?id=13']
['//192.168.1.22:8080/addressbook/edit.php?id=9', '//192.168.1.22:8080/addressbook/edit.php?id=10', '//192.168.1.22:8080/addressbook/edit.php?id=11', '//192.168.1.22:8080/addressbook/edit.php?id=13', '//192.168.1.22:8080/addressbook/edit.php?id=14']

You need to print links outside of for loop.

def get_contact_id(self):
    wd = self.app.wd
    elements = wd.find_elements_by_xpath("//a[contains(@href, 'edit.php?id')]")
    print(elements)
    links = []
    for i in elements:
        link = i.get_attribute('href')
        links.append(link)
    print(links)

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