python - while循环不更新值

标签 python python-3.x beautifulsoup

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

我创建了一个 while 循环,当发现另一个 URL 时,应在其中更新 URL。我还添加了一个“times”变量来测试循环执行的次数。 (计数 = 4 => 最后版本次数 = 4)。然而,“次数”确实改变了,但 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 次。

最佳答案

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

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

关于python - while循环不更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55332323/

相关文章:

python - 传输异常

python-3.x - 使用 apply lambda 检查条件时,系列的真值不明确

python - 使用 BeautifulSoup 但从大文件中获取内存错误

python - 在 BeautifulSoup 解析中没有得到正确的响应

python - 使yfinance错误传播

用于英国境外邮政编码的 Python 正则表达式

python setup.py build_ext --include-dirs=/usr/include/gdal/不工作

python-3.x - 无法使用 pip3 安装 DjangoRestFramework?

python - 这个 "studentrecord"是什么?

Python3 - BeautifulSoup - 获取两个标签之间的值,其中值介于