从for循环追加列表

时间:2019-07-16 01:05:45

标签: python list append

我正在尝试使用从网页收集的链接填充列表。 该列表出乎意料的结果。 我使用的代码有什么问题?

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)

我希望得到:

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']

相反,我得到了:

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']

1 个答案:

答案 0 :(得分:0)

您需要在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)