当某个字符串没有出现在 Python 中时退出 while 循环

Exit a while loop, when a certain string doesn't appear in Python

我有一个程序可以从 url 中获取 xml sheet。这个 xml 上有很多数据,因此我一次只能看到 2500 'profiles'。

在这些 xml 配置文件中,我要求程序提取每个用户的 ID 号,这是一个 8 位代码。我还要求程序将 url 提取到下一个 2500 个配置文件,这是我使用 endswith() 函数完成的。

我的问题是在最后一页数据中没有 link 可以匹配,我需要循环停止,同时还要拉出最后一组 ID

这是我目前的情况:

myURL = 'blah'

while myUrl is not '':
    info = request.get(myUrl)

将其转换为字符串列表

    end_of_new_link = "thingy"
    for link in list
        if link.endswith(end_of_new_link)
            myUrl = link

我格式化 link 以便我可以在 while 循环的下一次迭代中使用它

     elif link.startswith(IDNUMBER)
          listIDs.append(link)

有没有办法可以将变量 myUrl 设置为空字符串以退出 while 循环,或者我的逻辑在这里全错了

我认为最简单的方法是使用两个变量而不是一个变量。

lastUrl, nextUrl = None, 'blah'

while nextUrl != lastUrl:
    # url gets consumed and becomes "old"
    info, lastUrl = request.get(nextUrl), nextUrl

稍后...

end_of_new_link = "thingy"
for link in list
    if link.endswith(end_of_new_link)
        nextUrl = link # now it's different so the loop will continue

当然,如果您愿意,您可以将其不必要地抽象化,并有一个包装对象来标记自上次读取以来其封装数据是否已更改(或只是已设置)。