获取 return URL 代码 python urllib

Getting return codes of URLs python urllib

我有一个 URL 列表,其中一些现在不起作用。我想解析该列表并获取这些 URL 的 return 代码并将它们存储在数据框中。 我有以下代码:

for url in df['URL'][]:
print(url)
try:
    #print(urllib2.urlopen(url).getcode())
    df['returncode']=urllib2.urlopen(url).getcode()
except:
    df['returncode']='Obsolete'
    #print('obsolete')

我得到的是所有“过时”的列。

df['returncode']:
0         Obsolete
1         Obsolete
2         Obsolete
3         Obsolete
4         Obsolete
5         Obsolete
6         Obsolete
7         Obsolete
8         Obsolete
9         Obsolete
10        Obsolete
11        Obsolete

而如果我打印这些值,我可以看到不同的 return 代码。

http://study.com/odfv.html
obsolete
http://www.meghansfashion.com/uploads/2/1/2/9/21295692/2_75_orig.png
200
http://p16.muscdn.com/img/tos-maliva-p-0068/8ab65f6aac844cdf83526b5662720be3~c5_300x400.jpeg
200
http://config.88-f.net/hb/c1/pxbfwsp
obsolete

我做错了什么?

Getting return codes of URLs python urllib


您可以使用 requests 获取 url 上的 http 状态代码,即:

import requests
response = requests.get("https://google.com")
print (response.status_code)
# 200

您可以使用 urllib2 获取 http 响应代码。你是大多数 在那里,您只需要正确处理异常。 urllib2 当它收到错误的 http 响应时引发异常。

import urllib2

urls = ['http://www.google.com', 'http://google.com/does-not-exist']

for url in urls:
    try:
        res = urllib2.urlopen(url)
        code = res.getcode()
    except urllib2.HTTPError as err:
        code = err.getcode()

    print('{}: {}'.format(url, code))

这将输出:

http://www.google.com: 200
http://google.com/does-not-exist: 404

您在 DataFrame 中输入结果的方式不起作用。命令

df['returncode']= ...

将值放入 DataFrame 的 行。所以你最后看到的是找到的 last 值的十一倍。

要改进这一点,您需要将结果放入特定的行中。您可以像这样遍历行:

for index, row in df.iterrows():
    url = row['URL']
    print(url)
    try:
        #print(urllib2.urlopen(url).getcode())
        row['returncode']=urllib2.urlopen(url).getcode()
    except:
        row['returncode']='Obsolete'
        #print('obsolete')