为什么我的 python 进程在几次迭代后停止?



我不知道为什么下面的代码在几次迭代后停止运行。python进程将继续在终端中运行,但不会下载或检查任何文件。

有人可以帮忙吗?谢谢

#Manga downloader
#!python 3
import requests
import os
import bs4
import time
import urllib.request
import shutil
from pathlib import Path
url='http://www.mangareader.net/'
name=input("Enter comic name:")
chapterstart=int(input("Enter starting chapter number:"))
chapterend=int(input("Enter ending chapter number:"))
nameinput=name.replace(" ","-")
os.makedirs('Documents/Manga/',exist_ok=True)
directorylevel1='Documents/Manga/'+nameinput+'/'
os.makedirs(directorylevel1,exist_ok=True)
a=chapterstart
def imagesave(mangaUrl,filename,directorylevel2):
#res = requests.get(mangaUrl)
#print(res)
#res.raise_for_status()
fulldirectoryname=directorylevel2+filename
mangapath=Path(fulldirectoryname)
if mangapath.exists():
print(fulldirectoryname + ' exists. Moving on.')
else:
print('Downloading image %s...' %(filename))
req = urllib.request.Request(mangaUrl, headers={'User-Agent': 'Mozilla/5.0'})
with urllib.request.urlopen(req) as response: #open(fulldirectoryname,'wb') as outfile:
outfile=open(fulldirectoryname,'wb')
shutil.copyfileobj(response,outfile)
response = None
req = None
#imageFile=open(fulldirectoryname,'wb')
#for chunk in res.iter_content(10000000):
#    print(chunk)
#    imageFile.write(chunk)
#imageFile.close()
#for chapter 1 to 50
def main():
for a in range(chapterstart,chapterend+1):
b=str(a)
directorylevel2=directorylevel1+b+'/'
os.makedirs(directorylevel2,exist_ok=True)
c=str(a+1)
url='http://www.mangareader.net/'+nameinput+'/'+b
stopurl='http://www.mangareader.net/'+nameinput+'/'+c
res = requests.get(url)
res.raise_for_status
soup=bs4.BeautifulSoup(res.text,"lxml")
mangaElem = soup.select('#imgholder img')
#the imgholder is the div class name then img is the image inside
#print(url)
#for pages 1 to end
while url !=stopurl:
if mangaElem == [ ]:
print('Could not find image')
break
else:
mangaUrl=mangaElem[0].get('src')
filename=mangaElem[0].get('alt')+'.jpg'
imagesave(mangaUrl,filename,directorylevel2)
prevLink=soup.select('#imgholder a')[0]
url='http://www.mangareader.net'+prevLink.get('href')
res = requests.get(url)
res.raise_for_status
soup=bs4.BeautifulSoup(res.text,"lxml")
mangaElem = soup.select('#imgholder img')
#soup = None
a=a+1
print('Done')
if __name__ == "__main__":
main()

要考虑的忧虑:

您的代码运行得很平稳 - 也就是说,它以计算机速度从站点抓取文件。 该网站希望以人类的速度抓取文件——如果它更快地检测到任何内容,它可能会在几个文件后阻止访问。 我看到您导入了time但没有使用它 - 也许您打算在访问之间添加time.sleep(1)以防止被锁定。

几年前,当访问速度太快时,我偶尔会手动阻止在线科学数据库中的网站。 我知道政府数据库记录了访问速度(每秒页数(,程序应该保留在以下以避免被阻止。

做一个好网友。 值得一试。

最新更新