在处理包含多个链接的Python列表时,有时会遇到无效或错误的链接。为了跳过这些错误链接并继续处理其余的链接,可以使用异常处理机制(try-except)来捕获和处理这些错误。
以下是一个示例,展示了如何使用requests
库来处理链接,并跳过错误链接:
import requests
# 示例链接列表
links = [
"https://www.google.com",
"https://www.invalid-link.com", # 这是一个无效链接
"https://www.github.com"
]
# 遍历链接列表
for link in links:
try:
# 尝试发送GET请求
response = requests.get(link)
# 检查响应状态码
if response.status_code == 200:
print(f"Successfully accessed {link}")
else:
print(f"Failed to access {link} with status code {response.status_code}")
except requests.exceptions.RequestException as e:
# 捕获所有请求异常
print(f"Error accessing {link}: {e}")
print("Finished processing links.")
requests
库:首先,确保你已经安装了requests
库。如果没有安装,可以使用以下命令安装:pip install requests
for
循环遍历每个链接。try
块尝试发送GET请求。except
块捕获所有请求异常(requests.exceptions.RequestException
),并打印错误消息。你还可以捕获特定类型的异常,以便更精细地处理不同类型的错误。例如:
import requests
links = [
"https://www.google.com",
"https://www.invalid-link.com",
"https://www.github.com"
]
for link in links:
try:
response = requests.get(link)
response.raise_for_status() # 如果状态码不是200-299,抛出HTTPError
print(f"Successfully accessed {link}")
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred for {link}: {http_err}")
except requests.exceptions.ConnectionError as conn_err:
print(f"Connection error occurred for {link}: {conn_err}")
except requests.exceptions.Timeout as timeout_err:
print(f"Timeout error occurred for {link}: {timeout_err}")
except requests.exceptions.RequestException as req_err:
print(f"An error occurred for {link}: {req_err}")
print("Finished processing links.")
在这个示例中,我们捕获了不同类型的请求异常,并分别处理它们:
requests.exceptions.HTTPError
:处理HTTP错误(如404, 500等)。requests.exceptions.ConnectionError
:处理连接错误。requests.exceptions.Timeout
:处理请求超时。requests.exceptions.RequestException
:捕获所有其他请求异常。领取专属 10元无门槛券
手把手带您无忧上云