您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Python和BeautifulSoup从网页下载.xls文件

使用Python和BeautifulSoup从网页下载.xls文件

您的脚本目前存在的问题是:

您的代码修改后的版本 获取正确的文件并尝试下载它们,如下所示:

from bs4 import BeautifulSoup
# Python 3.x
from urllib.request import urlopen, urlretrieve, quote
from urllib.parse import urljoin

# Remove the trailing / you had, as that gives a 404 page
url = 'https://www.rbi.org.in/Scripts/bs_viewcontent.aspx?Id=2009'
u = urlopen(url)
try:
    html = u.read().decode('utf-8')
finally:
    u.close()

soup = BeautifulSoup(html, "html.parser")

# Select all A elements with href attributes containing URLs starting with http://
for link in soup.select('a[href^="http://"]'):
    href = link.get('href')

    # Make sure it has one of the correct extensions
    if not any(href.endswith(x) for x in ['.csv','.xls','.xlsx']):
        continue

    filename = href.rsplit('/', 1)[-1]
    print("Downloading %s to %s..." % (href, filename) )
    urlretrieve(href, filename)
    print("Done.")

但是,如果运行此命令urllib.error.HTTPError: HTTP Error 403: Forbidden,即使文件可在浏览器中下载,也会注意到将引发异常。起初我以为这是引荐检查(以防止出现热链接),但是如果您在浏览器中观看请求(例如Chrome开发者工具),则会注意到初始http://请求也被阻止,然后Chrome尝试了https://请求对于同一文件

换句话说,请求必须通过HTTPS才能起作用(尽管页面中的URL表示什么)。为了解决这个问题,你需要重写http:,以https:使用的URL请求之前。以下代码将正确修改URL并下载文件。我还添加一个变量来指定输出文件夹,使用os.path.join以下命令将其添加文件名中:

import os
from bs4 import BeautifulSoup
# Python 3.x
from urllib.request import urlopen, urlretrieve

URL = 'https://www.rbi.org.in/Scripts/bs_viewcontent.aspx?Id=2009'
OUTPUT_DIR = ''  # path to output folder, '.' or '' uses current folder

u = urlopen(URL)
try:
    html = u.read().decode('utf-8')
finally:
    u.close()

soup = BeautifulSoup(html, "html.parser")
for link in soup.select('a[href^="http://"]'):
    href = link.get('href')
    if not any(href.endswith(x) for x in ['.csv','.xls','.xlsx']):
        continue

    filename = os.path.join(OUTPUT_DIR, href.rsplit('/', 1)[-1])

    # We need a https:// URL for this site
    href = href.replace('http://','https://')

    print("Downloading %s to %s..." % (href, filename) )
    urlretrieve(href, filename)
    print("Done.")
python 2022/1/1 18:34:18 有516人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶