【问题标题】:How to get size of a file from Webpage in BeautifulSoup如何从 BeautifulSoup 中的网页获取文件的大小
【发布时间】:2016-05-19 05:01:11
【问题描述】:

我在 Python 中使用BeautifulSoup

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

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

【问题讨论】:

    标签: python file beautifulsoup size html-parsing


    【解决方案1】:

    使用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
    

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

    【讨论】:

    • 哦,我没有看到这个页面已经提到它。但是,将其用于其他页面。谢谢!
    • @DarshilChauhan:很高兴为您提供帮助!
    【解决方案2】:

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

    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
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多