您的脚本目前存在的问题是:
您的代码的修改后的版本 将 获取正确的文件并尝试下载它们,如下所示:
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.")