【发布时间】: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