gpt4 book ai didi

python - urlopen 是否被延迟评估?

转载 作者:行者123 更新时间:2023-12-05 02:30:22 27 4
gpt4 key购买 nike

# Get the content type of a URL
def get_url_type(url: str) -> str:
r = urlopen(url)
header = r.headers
return header.get_content_type()

下面是只获取标题还是获取整个文档?

我正在使用它来检查它是否是 html 页面,以避免下载(大)文件。

最佳答案

似乎在 urlopen() 调用中只检索了 header 和一部分正文,其余部分在 read() 中获取。

在使用 wireshark 之类的工具进行测试时,您会发现即使您调用 urllib.urlopen('VeryLargeFile'),您最初仍然只会收到 header 和一些正文数据包。

但是,如果您只想知道页面的大小或其内容类型,您可以使用requests:

import requests

rh = requests.head(url)
header = rh.headers
content_type = header.get('content-type')

print(content_type)
# text/html; charset=UTF-8

关于python - urlopen 是否被延迟评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71890220/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com