鱼C论坛

 找回密码
 立即注册
查看: 2702|回复: 2

python 怎么检测的403啊?

[复制链接]
发表于 2017-10-7 22:20:46 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
爬取403的网页,并且把是403的网页保存下来!
问题就在于怎么检测403??
求助啊!!!
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-10-7 23:14:01 | 显示全部楼层
异常处理,判断异常代码
如:
写法1:
import urllib.request
from urllib.error import *

req = urllib.request.Request("http://www.fishc.com/ooxx.html")
try:
    urllib.request.urlopen(req)
except HTTPError as e:
    print(e.code)
    print(e.reason)
    print(e.read())
except URLError as e:
    print(e.reason)

写法2:(推荐)
try:
    response = urlopen(req)
except URLError as e:
    if hasattr(e, 'reason'):
        print(e.reason)        
    elif hasattr(e, 'code'):
        print(e.code)
    else:
        pass
        
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-10-8 11:13:15 | 显示全部楼层
好像Python 3 没有实现403,404... 处理。

可以试试http.client

文档链接:https://docs.python.org/3/library/http.client.html#examples

  1. >>> import http.client
  2. >>> conn = http.client.HTTPSConnection("www.python.org")
  3. >>> conn.request("GET", "/")
  4. >>> r1 = conn.getresponse()
  5. >>> print(r1.status, r1.reason)
  6. 200 OK
  7. >>> data1 = r1.read()  # This will return entire content.
  8. >>> # The following example demonstrates reading data in chunks.
  9. >>> conn.request("GET", "/")
  10. >>> r1 = conn.getresponse()
  11. >>> while not r1.closed:
  12. ...     print(r1.read(200))  # 200 bytes
  13. b'<!doctype html>\n<!--[if"...
  14. ...
  15. >>> # Example of an invalid request
  16. >>> conn.request("GET", "/parrot.spam")
  17. >>> r2 = conn.getresponse()
  18. >>> print(r2.status, r2.reason)
  19. 404 Not Found
  20. >>> data2 = r2.read()
  21. >>> conn.close()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-12-24 07:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表