【问题标题】:While loop does not update valueWhile循环不更新值
【发布时间】:2019-03-25 06:32:37
【问题描述】:

我是 Python 新手,最近无法很好地使用 while 循环 - 变量没有更新新值!

我创建了一个 while 循环,当找到另一个 URL 时应在其中更新 URL。我还添加了一个“时间”变量来测试循环执行的次数。 (计数 = 4 => 上一个版本的次数 = 4)。然而,'times' 确实改变了,但 URL 只改变了 1 次。

URL = input('Enter - ')
count = input('Enter count: ')
pos = input('Enter position: ')

times = 0
links = list()
while times < int(count):
    html = urlopen(URL, context=ctx).read()
    soup = BeautifulSoup(html, "html.parser")

    tags = soup('a')
    for tag in tags:
        link = tag.get('href',None)
        links.append(link)
    URL = links[int(pos) - 1]
    times = times + 1
name = re.findall('known_by_(.+).html',URL)
print(name)

我希望更新 URL 并且循环再次运行 4 次,但只获得第一次循环运行时的结果。同时,'times' 变量被添加了足够多的 4 次。

【问题讨论】:

  • 我还建议您使用更多的“Pythonic”循环:for _ in range(int(count)): 这将允许您不使用times 变量,因此您可能会出现潜在错误的地方更少。

标签: python python-3.x beautifulsoup


【解决方案1】:

您的循环看起来应该运行count 次,每次都执行完全相同的操作。但是,最后两行没有缩进,所以它们在循环之外。这意味着它们只会在循环完成时运行一次。

如果要在每次循环运行时运行最后两行,则需要将它们缩进到与times = times + 1 相同的级别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2012-09-09
    • 2018-08-17
    相关资源
    最近更新 更多