Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/jenkins/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
避免在Python Urlopen中下载文件_Python_Urllib - Fatal编程技术网

避免在Python Urlopen中下载文件

避免在Python Urlopen中下载文件,python,urllib,Python,Urllib,我正在使用python构建一个网络爬虫。但是urlopen(url)下载页面中的文件。我只想阅读html,如果url指向可下载的文件,则跳过 我试过使用超时 urlopen(url, timeout = 5).read() 这样可以避免使用大文件,但这似乎不起作用 我还想列出常见的文件扩展名,并在url以扩展名结尾时跳过url flag = False extensions = ['.zip', '.mp3',....] for extension in extensions: if

我正在使用python构建一个网络爬虫。但是
urlopen(url)
下载页面中的文件。我只想阅读html,如果url指向可下载的文件,则跳过

我试过使用超时

urlopen(url, timeout = 5).read()
这样可以避免使用大文件,但这似乎不起作用

我还想列出常见的文件扩展名,并在url以扩展名结尾时跳过url

flag = False
extensions = ['.zip', '.mp3',....]
for extension in extensions:
    if url.endswith(extension):
        flag = True
        continue
if not flag:
    x = urlopen(url).read()
但我想这种方法不会很有效


有什么想法吗?

您可以使用
内容类型
HTTP头来确定它是HTML还是其他内容:

x= urlopen(url)
if 'text/html' in x.headers.get('Content-Type'):
    x= x.read()

要缩小要检查的文件内容量,请在检查文件内容之前先检查
retcode

doc = urllib.urlopen(url, timeout=5)
if doc and doc.getCode() == 200 and doc.headers.get('Content-Type').startswith("text/html"):
    x = doc.read()
你可以通过


我想他想要在打开url之前?你不能直接,但你可以做一个
请求,只获取头,然后检查它们,确定是否要做一个完整的
获取
In [8]: import requests

In [9]: h = requests.head("http://stackoverflow.com/questions/37771237/avoid-downloadable-files-in-python-urlopen")

In [10]: if "text/html" in h.headers["content-type"]:
   ....:     content = requests.get("http://stackoverflow.com/questions/37771237/avoid-downloadable-files-in-python-urlopen").text
   ....: