它不会转到第三个网址-

try:
        "code here..."
except requests.exceptions.ConnectionError:
    pass  # doesn't pass to try:


这是代码-

import requests

try:
    for url in ['google.com', 'skypeassets.com', 'yahoo.com']:

        http = ("http://")
        url2 = (http + url)
        page = requests.get(url2)

        if page.status_code == 200:
            print('Success!')
        elif page.status_code == 404:
            print('Not Found.')

except requests.exceptions.ConnectionError:
    print("This site cannot be reached")
        pass


输出-

成功!
此网站无法打开
(对于第三个网址-应该说-成功!,但跳过)

最佳答案

try except一次只能在其主体或块内部捕获一个异常。
这意味着您必须在for循环中使用它。

import requests

for url in ['google.com', 'skypeassets.com', 'yahoo.com']:
    try:
        http = "http://"
        url2 = http + url
        page = requests.get(url2)

        if page.status_code == 200:
            print('Success!')
        elif page.status_code == 404:
            print('Not Found.')

    except requests.exceptions.ConnectionError:
        print("This site cannot be reached")

关于python - 无法使用Try,Except进入第三URL进行查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56242599/

10-11 20:30