繁体   English   中英

从for循环追加列表

[英]Appending list from a 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)

我希望得到:

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

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