Нужна помощь в определении условия окончания - PullRequest
0 голосов
/ 05 июня 2011

Я написал скрипт на 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 = ">|"):

но, делая это, я фактически отправляю пропуск на последнюю страницу, прежде чем сценарий сможет выполнить предназначенную цель.

1 Ответ

1 голос
/ 05 июня 2011

Когда вы переходите по ссылке «Далее» из последнего комикса xkcd, к URL добавляется хэш-тег.Попробуйте использовать следующее.

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