gpt4 book ai didi

python - 如何使用 python 跳过存储库中不存在的文件?

转载 作者:数据小太阳 更新时间:2023-10-29 02:06:02 26 4
gpt4 key购买 nike

我想从问题跟踪系统一个一个地下载 xml 文件。当存储库中不存在文件时,它会产生错误消息。我包含了 python 脚本以更好地理解我的问题。

我的代码:

import urllib.request
for i in range(0,1000):
issue_id1='DERBY-'+str(i)
url ="https://issues.apache.org/jira/si/jira.issueviews:issue-xml/"+issue_id1+'/'+issue_id1+'.xml'
s=urllib.request.urlopen(url)
contents = s.read()
file = open(issue_id1+'.xml', 'wb')
file.write(contents)

file.close()

堆栈跟踪:

Traceback (most recent call last):
File "/PhP/Learning/xmldownlaod.py", line 10, in <module>
s=urllib.request.urlopen(url)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 161, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 469, in open
response = meth(req, response)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 579, in http_response
'http', request, response, code, msg, hdrs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 507, in error
return self._call_chain(*args)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 441, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/urllib/request.py", line 587, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found

最佳答案

Python 使用 "try except"错误处理 block

import urllib.request
from urllib.error import URLError # the docs say this is the base error you need to catch
for i in range(0,1000):
issue_id1='DERBY-'+str(i)
url ="https://issues.apache.org/jira/si/jira.issueviews:issue-xml/"+issue_id1+'/'+issue_id1+'.xml'
try:
s=urllib.request.urlopen(url)
contents = s.read()
except URLError:
print('an error occurred while fetching: "{}"'.format(url))
continue # skip this url and proceed to the next
file = open(issue_id1+'.xml', 'wb')
file.write(contents)

关于python - 如何使用 python 跳过存储库中不存在的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43084036/

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