【问题标题】:Python: Avoiding downloading html when taken to "page doesn't exist" errorPython:在出现“页面不存在”错误时避免下载 html
【发布时间】:2019-01-07 16:04:51
【问题描述】:

我正在自学网页抓取,并想使用requests 下载一堆 .pgn 文件(基本上是文本文件)。文件名采用日期的形式,但不是严格按时间顺序排列的。我对可能的日期运行了一个循环,但如果索引日期与文件不对应,我仍然最终将filename.pgn 下载为带有错误页面 html 的文本文件。相反,我想要的是跳过这些日期。

这是一个例子:

如果我跑:

filename = 'games9jul18.pgn'
url = 'https://www.chesspublishing.com/p/9/jul18/'+filename
response = requests.post(url, data=payload)
with open(filename, 'wb') as e:
    e.write(response.text)

通过payload 中的适当身份验证,将保存正确的文件games9jul18.pgn。但如果我跑:

filename = 'games9aug18.pgn'
url = 'https://www.chesspublishing.com/p/9/aug18/'+filename
response = requests.post(url, data=payload)
with open(filename, 'wb') as e:
    e.write(response.text)   

我仍然得到一个保存的文件games9aug18.pgn,但它不是一个“真正的”pgn 文件,而是一个错误页面的 html 文本文件。在我的浏览器上导航到错误页面,它没有错误代码,但有一大块文本您询问的页面可能已被删除,或者可能从未存在。

不幸的是,由于日期结构不一致,无法仅循环与实际文件对应的文件名。如果到达错误页面,如何添加不创建.pgn文件的条件?

【问题讨论】:

    标签: python loops python-requests http-status-code-404


    【解决方案1】:

    您应该检查响应状态。 “找不到页面”是 404,因此您可以检查该代码,甚至检查成功的请求,即 200:

    response = requests.post(url, data=payload)
    if response.status == 200:
        with...
    

    【讨论】:

      【解决方案2】:

      当页面未找到时,您可以检查成功请求的代码:200:404。

      if response.status_code ==200:
          with open(filename, 'wb') as e:
              e.write(response.text)
      

      【讨论】:

        猜你喜欢
        • 2020-07-13
        • 1970-01-01
        • 1970-01-01
        • 2019-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-28
        • 1970-01-01
        相关资源
        最近更新 更多