python - 我如何确定给定网址中是否存在任何内容

标签 python http url

<分区>

我如何使用 python 确定给定 url 中的任何内容是否存在于网络中?它可以是 html 页面或 pdf 文件,应该无关紧要。 我试过本页中写的解决方案 http://code.activestate.com/recipes/101276/ 但是当它是 pdf 文件或任何东西时它只返回 1。

最佳答案

您需要检查 HTTP 响应代码。 Python 示例:

from urllib2 import urlopen
code = urlopen("http://example.com/").code

4xx 和 5xx 代码可能意味着您无法从此 URL 获得任何内容。 4xx 状态代码描述客户端错误(如“404 Not found”),5xx 状态代码描述服务器错误(如“500 Internal server error”):

if (code / 100 >= 4):
   print "Nothing there."

链接:

关于python - 我如何确定给定网址中是否存在任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1966086/

相关文章:

python-2.7 - 使用网页回放录制 HTTPS 网页

html - 在 self 页面上提交 HTML 表单

python - FeatureTools:处理多对多关系

python - Django项目——开发与生产

没有逗号的Python打印

http - Haskell SimpleHTTP 获取响应代码

http - 加载数据时客户端异常

url - 在 url 中路由 Zend Framework 2 语言

c# - 使用 C#,如何为项目中的 HTML 文件设置 Url 属性?

python - 在命令行中将文件名传递给 python 脚本