【问题标题】:Categorise Good and Bad urls分类好网址和坏网址
【发布时间】:2020-04-29 22:35:54
【问题描述】:

我有一个大约 6000 个 URL 的列表,如果它的 响应代码是 200(或)不是,我必须检查每个 URL。 通过使用使用 urllib 的普通 request.get(),它是加载整个 HTML 页面并返回响应代码需要花费大量时间。

有没有什么办法只是获取 URL 的代码,而不是在后端完全加载网页?

【问题讨论】:

标签: python-3.x http httpwebresponse


【解决方案1】:

你应该只是 ping 他们:

import os
hosts = [
    'google.com', 
    ...
]

for host in hosts:
    response = os.system(f"ping -c 1 {host}")
    if response == 0:
        print('host is up')
    else:
        print('host is down')

【讨论】:

  • @Monica,对于“careers.microsoft.com”,响应代码为 512,未分配,但 URL 应为 200。请您告诉修复此问题
  • "ping" 只会在主机可访问并且响应 ICMP(not HTTP)ping 请求时通知您。
【解决方案2】:

您可以使用HEAD 方法仅获取 URL 的标头详细信息。它看起来像这样:

from urllib.request import Request, urlopen

urls = [
       'http://google.com',
]

def custom_get_method():
    return 'HEAD'

for url in urls:
    req = Request(url)
    req.get_method = custom_get_method
    res = urlopen(req)
    if res.status == 200:
       print("Up")
    else:
       print("Down")

代码已改编自https://stackoverflow.com/a/4421485/690576

【讨论】:

    猜你喜欢
    • 2011-02-10
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 2010-12-25
    • 2010-10-28
    • 1970-01-01
    • 2012-10-15
    • 2016-03-11
    相关资源
    最近更新 更多