BeautifulSoup 如何从网页中获取文件的大小

How to get size of a file from Webpage in BeautifulSoup

我在 Python 中使用 BeautifulSoup

我想从网页获取可下载文件的大小。例如,this 页面有一个 link 可以下载 txt 文件(通过单击 "save")。如何获取该文件的大小(以字节为单位)(最好不下载)?

如果BeautifulSoup中没有选项,请提出Python内外的其他选项。

使用 requests 包,您可以向提供文本文件的 URL 发送 HEAD 请求,并检查 header 中的 Content-Length :

>>> url = "http://cancer.jpl.nasa.gov/fmprod/data?refIndex=0&productID=02965767-873d-11e5-a4ea-252aa26bb9af"
>>> res = requests.head(url)
>>> res.headers
{'content-length': '944', 'content-disposition': 'attachment; filename="Lab001_A_R03.txt"', 'server': 'Apache-Coyote/1.1', 'connection': 'close', 'date': 'Thu, 19 May 2016 05:04:45 GMT', 'content-type': 'text/plain; charset=UTF-8'}
>>> int(res.headers['content-length'])
944

如您所见,大小与 the page 中提到的相同。

由于页面提供了这些信息,如果您相信,可以从页面正文中提取:

import re
import requests
from bs4 import BeautifulSoup


url = 'http://edrn.jpl.nasa.gov/ecas/data/product/02965767-873d-11e5-a4ea-252aa26bb9af/1'
content = requests.get(url).text
soup = BeautifulSoup(content, 'lxml')

p = re.compile(r'^(\d+) bytes$')
el = soup.find(text=p)
size = p.match(el.string).group(1)

print(size)  # 944