【问题标题】:How to modify this script to check for HTTP status (404, 200)如何修改此脚本以检查 HTTP 状态(404、200)
【发布时间】:2014-10-17 14:10:21
【问题描述】:

我目前正在使用以下脚本加载 URL 列表,然后检查每个 URL 的来源以获取错误字符串列表。如果在源中未找到错误字符串,则认为 URL 有效并写入文本文件。

如何修改此脚本以检查 HTTP 状态?如果 URL 返回 404,它将被忽略,如果返回 200,则 URL 将被写入文本文件。任何帮助将不胜感激。

import urllib2
import sys

error_strings = ['invalid product number', 'specification not available. please contact   customer services.']

def check_link(url):
if not url:
    return False
f = urllib2.urlopen(url)    
html = f.read()
result = False
if html:
    result = True
    html = html.lower()
    for s in error_strings:
        if s in html:
            result = False
            break
return result


if __name__ == '__main__':
if len(sys.argv) == 1:
    print 'Usage: %s <file_containing_urls>' % sys.argv[0]
else:
    output = open('valid_links.txt', 'w+')
    for url in open(sys.argv[1]):
        if(check_link(url.strip())):
            output.write('%s\n' % url.strip());
    output.flush()
    output.close()

【问题讨论】:

    标签: python request


    【解决方案1】:

    你可以稍微改变你对urlopen的调用:

    >>> try:
    ...     f = urllib2.urlopen(url)
    ... except urllib2.HTTPError, e:
    ...     print e.code
    ...
    404
    

    使用e.code,您可以检查它是否在您身上出现 404。如果你没有点击except 块,你可以像现在一样使用f

    【讨论】:

      【解决方案2】:

      urlib2.urlopen 用其他一些方法返回一个类似文件的对象,其中之一:getcode() 是你要找的,只需添加一行:

      if f.getcode() != 200:
          return False
      

      在相关的地方

      【讨论】:

      • 此方法不适用于 404。如果你urlopen一个不存在的站点,它会在你通过这个方法检查代码之前抛出一个异常。
      • 很公平,我查看了文档,发现了一些有用的东西,但略有误解。我自己,我尽可能使用requests
      【解决方案3】:

      试试这个。你可以用这个

       def check_link(url):
              if not url:
                  return False
              code = None
              try:
                  f = urllib2.urlopen(url)
                  code = f.getCode()
              except urllib2.HTTPError, e:
                  code = e.code
              result = True
              if code != 200:
                  result = False
              return result
      

      或者,如果您只需要维护一个无效代码字符串列表并对其进行检查,则如下所示。

      def check_link(url):
          if not url:
              return False
          code = None
          try:
              f = urllib2.urlopen(url)
              code = f.getCode()
          except urllib2.HTTPError, e:
              code = e.code
      
          result = True
          if code in invalid_code_strings:
               result = False
      
          return result
      

      【讨论】:

      • 这不起作用。如果您的 URL 不存在,您的urlopen 会出现异常。使用 URL http://www.google.com/NOTREAL 尝试此代码并注意抛出的 urllib2.HTTPError
      • +1 你是对的。不成功的状态码似乎是通过异常返回的。
      猜你喜欢
      • 1970-01-01
      • 2023-03-30
      • 2019-06-17
      • 2017-05-29
      • 1970-01-01
      • 2013-01-09
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多