尝试不同版本的网址 - Python

Try different versions of website addresses - Python

我正在使用列表 "names" 中的变量从网站请求值点:

names = ['A', 'B', 'C', 'D', 'E']

其实我的名字值比这个多很多

计划是迭代以下地址并像这样填写我的变量:

def get_values(name):
    res = requests.get('www.example.com/tb/' + name)

for name in names:
    get_values(name)

问题是,对于不同的值,地址的一部分会更改为三个不同的值(tb、az 和 dm)(对于不同的名称,它们始终相同):

出于这个原因,在我上面的代码中,只下载了 A 和 B 的值。 (并且将变量分配给名称是不切实际的,反之亦然。)

所以我获得正确 URL 的计划是用 if/else 解决这个问题:

try:
    r = requests.get('www.example.com/tb/' + stock)
    if r.status_code == 200:
        url = 'www.example.com/tb/' + stock
    else:
        r = requests.get('www.example.com/az/' + stock)
        if r.status_code == 200:
            url = 'www.example.com/az/' + stock
        else:
            url = 'www.example.com/dm/' + stock
except:
    pass

correctUrl = requests.get(url)

这只给出了一个变量的值(例如 tz)。 我也曾尝试使用 try 和 except 以及 try/except 和 if/else 的一些变体找到解决方案,但它不起作用。

如果有人能告诉我如何验证列表中每个名字的正确地址,那就太好了。或者什么是最pythonic的方式来做到这一点。不幸的是,我无法在 Whosebug 或 google.

上找到方法

您可以遍历可能的 url,直到获得代码 200:

def get_url(name):
    for sub in ('tb', 'az', 'dm'):
        url = f'www.example.com/{sub}/{name}'
        r = requests.get(url)
        if r.status_code == 200:
            return url
    return None    

for name in names:
    url = get_url(name)
    print(url)

Obviously, it would be much better if you could store those paths within your names, something like [(tb, A), (tb, B), (az, C), ...]. But i assume you can't?