[英]While loop does not update value
我是 Python 新手,最近不能很好地使用 while 循環 - 變量沒有更新新值!
我創建了一個 while 循環,當找到另一個 URL 時,將在其中更新 URL。 我還添加了一個“times”變量來測試循環執行的次數。 (計數 = 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 次。
您的循環看起來應該運行count
次,每次都做完全相同的事情。 但是,最后兩行沒有縮進,因此它們在循環之外。 這意味着它們只會在循環完成后運行一次。
如果您想在每次循環運行時運行最后兩行,您需要將它們縮進到與times = times + 1
相同的級別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.