问个问题哦大佬们。如下程序,要实现的功能就是测试ip地址的网站状态码然后将结果存储到数据库里。然后直接想着直接request.get效率有点低就加了个并发。这边问题就是我没办法把所有的结果都正确的导入到数据库。如果运行如下示例,就会报response是局部变量这种“UnboundLocalError: local variable 'response' referenced before assignment”。如果将insert语句加到try里面只能导入存在网站状态码的,如果同时加到try和except里面,except里面也会出现出现unboundlocalerror的报错。把获取response值的语句放到try外面更不行了,直接拦截不住异常直接结束程序。学艺不精还请路过大佬指教啊!
```python
# 遍历文本文件中的每一行并测试 URL
count = 0
count_200 = 0
count_404 = 0
count_403 = 0
count_502 = 0
count_error = 0
count_else = 0
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = []
for row in reader:
ipv6_address = row[0]
url = 'https://[' + ip_address + ']/' # 使用正确的列名
futures.append(executor.submit(requests.get , url , headers=headers , verify=False , timeout=3))
count += 1
for future in concurrent.futures.as_completed(futures):
try:
response = future.result()
status_code = response.status_code
if status_code == 200:
count_200 += 1
elif status_code == 404:
count_404 += 1
elif status_code == 403:
count_403 += 1
elif status_code == 502:
count_502 += 1
else:
count_else += 1
except Exception as e:
status_code = -1
count_error += 1
insert_query = f"INSERT INTO {table_name} (id, ip_address, status_code) VALUES (NULL, '{response.url}', {status_code})"
cursor.execute(insert_query)
# 提交更改并关闭连接
cnx.commit()
cursor.close()
cnx.close()
```