gpt4 book ai didi

python - 需要帮助指定结束 while 条件

转载 作者:行者123 更新时间:2023-12-04 16:21:04 25 4
gpt4 key购买 nike

我写了一个 Python 脚本来下载所有 xkcd漫画图像。唯一的问题是当它到达最后一个时我无法告诉它停止......这是我到目前为止所拥有的。

import re, mechanize
from urllib import urlretrieve
from BeautifulSoup import BeautifulSoup as bs

baseUrl = "http://xkcd.com/1/" #Specify the first comic page
br = mechanize.Browser() #Create a browser

response = br.open(baseUrl) #Create an initial response

x = 1 #Assign an initial file name
while (SomeCondition):
soup = bs(response.get_data()) #Create an instance of bs that contains the response data
img = soup.findAll('img')[1] #Get the online file path of the image
localFile = "C:\\Comics\\xkcd\\" + str(x) + ".jpg" #Come up with a local file name
urlretrieve(img["src"], localFile) #Download the image file
response = br.follow_link(text = "Next >") #Store the response of the next button
x += 1 #Increase x by 1
print "All xkcd comics downloaded" #Let the user know the images have been downloaded

最初我所拥有的是
while br.follow_link(text = "Next >") != br.follow_link(text = ">|"):

但是通过这样做,我实际上在脚本有机会执行预期目的之前将跳转到最后一页。

最佳答案

当您点击最新 xkcd 漫画中的“下一个”链接时,该 URL 会附加一个哈希标签。尝试使用以下方法。

while not br.geturl().endswith("#"):
...

关于python - 需要帮助指定结束 while 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6240865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com