避免 Python Urlopen 中的可下载文件

Avoid downloadable files in Python Urlopen

我正在使用 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()

但我想这种方法不会很有效。

有什么想法吗?

您可以使用 Content-Type HTTP header 来确定它是 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()

你可以通过 python requests

In [8]: import requests

In [9]: h = requests.head("")

In [10]: if "text/html" in h.headers["content-type"]:
   ....:     content = requests.get("").text
   ....: