[英]How to get size of a file from Webpage in BeautifulSoup
我在Python中使用BeautifulSoup
。
我想從網頁上獲取可下載文件的大小。 例如, 此頁面有一個下載txt
文件的鏈接(通過單擊“保存”)。 如何獲取該文件的大小(以字節為單位)(最好不要下載)?
如果BeautifulSoup
沒有選項,那么請在Python內外建議其他選項。
使用requests
包,您可以向提供文本文件的URL發送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
如您所見,尺寸與頁面上提到的相同。
由於頁面提供了這些信息,如果你相信它,你可以從頁面的主體中提取它:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.