【发布时间】:2019-06-05 11:14:11
【问题描述】:
我是 python 世界的新手,我想做网页抓取。
我想从以下网站下载一些 xls 文档到特定位置文件夹。 (例如桌面)
您能帮我解决这个问题吗?
网站是
https://www.ici.org/research/stats
我已经尝试了可用于类似问题的代码,但我没有设法让它们适用于我的案例:(
非常感谢。
【问题讨论】:
标签: web web-scraping download xls
我是 python 世界的新手,我想做网页抓取。
我想从以下网站下载一些 xls 文档到特定位置文件夹。 (例如桌面)
您能帮我解决这个问题吗?
网站是
https://www.ici.org/research/stats
我已经尝试了可用于类似问题的代码,但我没有设法让它们适用于我的案例:(
非常感谢。
【问题讨论】:
标签: web web-scraping download xls
要使用 BeautifulSoup,您首先需要了解 html 源代码的结构。你可以通过简单的谷歌搜索找到一些基本教程。
但最基本的是 html 代码包含带有 tags 的元素,而这些标签带有 attributes。您要查找的内容位于<a> 标签下,对应的链接为href 属性。所以我们需要找到所有<a>标签,这些标签有一个href属性,Excel扩展名为xls。
您可以通过检查页面来查看这一点(右键单击页面并选择检查或 ctrl-shift-I,以打开开发工具窗格。然后您可以单击以找到您需要的相应部分html 代码)并查看 html 源代码:
一旦你有了这些,你将遍历它们以打开并保存。我们也将只针对那些标记元素的文本/内容中包含“补充:全球公共表”的情况。
只需确保选择正确的根目录即可将其保存在上面写着output = open('C:/path/to/desktop/' + filename, 'wb')的位置:
import os
import requests
from bs4 import BeautifulSoup
desktop = os.path.expanduser("~/Desktop")
url = 'https://www.ici.org/research/stats'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
excel_files = soup.select('a[href*=xls]')
for each in excel_files:
if 'Supplement: Worldwide Public Tables' in each.text:
link = 'https://www.ici.org' + each['href']
filename = each['href'].split('/')[-1]
if os.path.isfile(desktop + '/' + filename):
print ('*** File already exists: %s ***' %filename)
continue
resp = requests.get(link)
output = open(desktop + '/' + filename, 'wb')
output.write(resp.content)
output.close()
print ('Saved: %s' %filename)
【讨论】: