【发布时间】:2016-01-06 12:10:42
【问题描述】:
我想从本网站下载所有.xls或.xlsx或.csv到指定文件夹。
https://www.rbi.org.in/Scripts/bs_viewcontent.aspx?Id=2009
我研究了 mechanize、beautiful soup、urllib2 等。Mechanize 在 Python 3 中不起作用,urllib2 在 Python 3 中也有问题,我寻找了解决方法,但我找不到。所以,我目前正在尝试使用 Beautiful Soup 使其工作。
我找到了一些示例代码并尝试修改它以适应我的问题,如下 -
from bs4 import BeautifulSoup
# Python 3.x
from urllib.request import urlopen, urlretrieve, quote
from urllib.parse import urljoin
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)
for link in soup.select('div[webpartid] a'):
href = link.get('href')
if href.startswith('javascript:'):
continue
filename = href.rsplit('/', 1)[-1]
href = urljoin(url, quote(href))
try:
urlretrieve(href, filename)
except:
print('failed to download')
但是,当运行此代码时,不会从目标页面提取文件,也不会输出任何失败消息(例如“下载失败”)。
- 如何使用 BeautifulSoup 从页面中选择 Excel 文件?
- 如何使用 Python 将这些文件下载到本地文件?
【问题讨论】:
-
您能描述一下您的代码“不起作用”的原因吗?发布的代码缩进错误,因此根本无法运行。
-
代码有时只是运行,但从未创建任何文件。关于缩进,我在发帖时道歉,我一定破坏了它,但请放心,当我运行代码时,我确实处理了缩进
-
我对此问题有一个可行的解决方案,但是问题已关闭,因此我无法再发布它。我已将其作为 Gist 发布在这里 gist.github.com/mfitzp/29522e2ac4057bf01745
-
@mfitzp 非常感谢,这行得通。像你这样的人确保语言永远不会消亡!!!!
-
添加这几行:
你可以提供mfitzp写的代码的下载位置
标签: python web-scraping beautifulsoup