如何使用python确定Web中是否存在任何给定URL?它可以是一个html页面或一个pdf文件,不应该是件事.香港专业教育学院尝试了在这个页面http://code.activestate.com/recipes/101276/写的解决方案, 但它只是返回一个1的pdf文件或任何东西.
sas*_*nin 15
您需要检查HTTP响应代码.Python示例:
from urllib2 import urlopen
code = urlopen("http://example.com/").code
Run Code Online (Sandbox Code Playgroud)
4xx和5xx代码可能意味着您无法从此URL获取任何内容.4xx状态代码描述客户端错误(如"404 Not found")和5xx状态代码描述服务器错误(如"500 Internal server error"):
if (code / 100 >= 4):
print "Nothing there."
Run Code Online (Sandbox Code Playgroud)
链接:
发送HEAD请求
import httplib
connection = httplib.HTTPConnection(url)
connection.request('HEAD', '/')
response = connection.getresponse()
if response.status == 200:
print "Resource exists"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8415 次 |
| 最近记录: |