我在Python中使用BeautifulSoup
。
我想从网页上获取可下载文件的大小。例如,this页面有一个下载txt
文件的链接(通过点击"保存")。如何获取该文件的大小(以字节为单位)(最好不要下载)?
如果BeautifulSoup
中没有选项,请在Python内外建议其他选项。
答案 0 :(得分:4)
使用requests
包,您可以向提供文本文件的网址发送HEAD
请求,并检查标题中的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中提到的相同。
答案 1 :(得分:3)
由于页面提供了此信息,如果您相信,可以从页面正文中提取:
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