HTTP 状态码是由服务器返回的,用于指示客户端请求的结果。状态码分为五类,每一类的第一个数字不同。以下是每一类的一些常见状态码及其解释:
1xx: 信息响应
- 100 Continue:表示服务器已经收到请求头部,客户端可以继续发送请求主体(在需要发送请求主体的情况下)。
- 101 Switching Protocols:表示服务器接受了客户端的请求,正在切换协议(如从 HTTP 切换到 WebSocket)。
2xx: 成功
- 200 OK:请求成功,并且服务器返回了请求的资源。
- 201 Created:请求成功,服务器创建了新的资源,通常用于 POST 请求。
- 204 No Content:请求成功,但没有返回任何内容,通常用于 DELETE 请求。
3xx: 重定向
- 301 Moved Permanently:请求的资源已永久移动到新位置,新的 URL 会在响应的 Location 头部中返回。
- 302 Found:请求的资源临时从不同的 URI 响应请求。
- 304 Not Modified:资源未被修改,可以使用缓存的版本。
4xx: 客户端错误
- 400 Bad Request:请求无效或格式错误,服务器无法处理。
- 401 Unauthorized:请求要求身份验证,通常用于需要登录的资源。
- 403 Forbidden:服务器理解请求但拒绝执行,客户端没有权限访问资源。
- 404 Not Found:请求的资源不存在,服务器找不到请求的 URL。
- 429 Too Many Requests:客户端在给定的时间内发送了太多请求。
5xx: 服务器错误
- 500 Internal Server Error:服务器内部错误,无法完成请求。
- 501 Not Implemented:服务器不支持请求的方法。
- 502 Bad Gateway:服务器作为网关或代理,从上游服务器收到无效响应。
- 503 Service Unavailable:服务器当前无法处理请求,通常是由于服务器过载或维护。
- 504 Gateway Timeout:服务器作为网关或代理,未能及时从上游服务器收到响应。
这些状态码可以帮助客户端理解服务器的响应并采取相应的行动 (from ChatGPT)
通过url读取并保存图片的举例:
file_path = 'xx'
df = pd.read_excel(file_path)
output = 'xx'
os.makedirs(output, exist_ok=True)
output_urls = 'xxxx'
start = 0
# end = 100000
with open(output_urls, 'a') as file:
for index, row in df.iloc[start:].iterrows():
url = row.loc['url']
parse = urlparse(url)
if not all([parse.scheme, parse.netloc]):
file.write('\n')
print(f"Skipping invalid URL at index {index}: {url}")
continue
try:
response = requests.get(url)
response.raise_for_status()
try:
image = Image.open(io.BytesIO(response.content)).convert('RGB')
image.save(os.path.join(output, f'{index:07d}.png'), 'PNG')
file.write(url+'\n')
except Exception as e:
print(f"Failed to save image from URL at index {index}: {url}. Error: {e}")
file.write('\n')
except requests.exceptions.RequestException as e:
file.write('\n')
print(f"Failed to download image from URL: {url}.")
if index % 1000 == 0:
print(f"Downloading {index}-th image. ")
其中 :
- parse = urlparse() 方法会解析url地址
from urllib.parse import urlparse
print(f'an incorrect url: {urlparse("abcde")}\n')
print(f'a correct url: {urlparse("https://editor.youkuaiyun.com/md?not_checkout=1&spm=1015.2103.3001.8066&articleId=140203311")}')
output:
an incorrect url: ParseResult(scheme='', netloc='', path='abcde', params='', query='', fragment='')
a correct url: ParseResult(scheme='https', netloc='editor.youkuaiyun.com', path='/md', params='', query='not_checkout=1&spm=1015.2103.3001.8066&articleId=140203311', fragment='')
- raise_for_status() 方法会检查响应对象中的 status_code 属性,如果状态码表明请求失败(即状态码在 400 到 599 之间),它会引发一个 requests.exceptions.HTTPError 异常
import requests
try:
response = requests.get("https://editor.youkuaiyun.com/md?not_checkout=1&spm=1015.2103.3001.8066&articleId=140203311", timeout=1)
response.raise_for_status()
print(f'status_code: {response.status_code}')
except Exception as e:
print(e)
try:
response = requests.get("https://editor.youkuaiyun.com/joking", timeout=1)
response.raise_for_status()
print(f'status_code: {response.status_code}')
except requests.exceptions.HTTPError as e:
print(e)
output:
status_code: 200
404 Client Error: Not Found for url: https://editor.csdn.net/joking