简体   繁体   English

从for循环追加列表

[英]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. 您需要在for循环之外打印links

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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