【问题标题】:scraping: download files from url抓取:从 url 下载文件
【发布时间】:2014-01-08 03:45:53
【问题描述】:

我想从这个page自动下载文件。

我尝试了很多方法,例如:

download.file
read.table
GET

但没有成功。我不是要代码,而是要任何提示/想法来处理这种情况。

【问题讨论】:

  • 对于 Python,一个常见的做法是使用BeautifulSoup
  • 为什么 download.file 不起作用?为我工作。
  • @Spacedman 你能告诉我这个吗?也许我错过了什么?
  • 向您展示我们所做的工作不是我们的工作。你的工作就是向我们展示你尝试过和失败过的东西。你没有这样做。请编辑您的问题并提供更多详细信息。
  • @Spacedman 你是对的(通常我会展示我尝试过的东西,也许你已经知道了)。我没有电脑(现在),一旦我得到它,我会编辑我的问题。

标签: python r curl selenium web-scraping


【解决方案1】:

使用BeautifulSoup的Python版本。

try:
    # Python 3.x
    from urllib.request import urlopen, urlretrieve, quote
    from urllib.parse import urljoin
except ImportError:
    # Python 2.x
    from urllib import urlopen, urlretrieve, quote
    from urlparse import urljoin

from bs4 import BeautifulSoup

url = 'http://oilandgas.ky.gov/Pages/ProductionReports.aspx'
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 真的很漂亮。
【解决方案2】:

这对我有用:

getIt = function(what,when){ 
     url=paste0("http://oilandgas.ky.gov/Production%20Reports%20Library/",
                 when,"%20-%20",what,
                "%20Production.xls")
     destfile=paste0("/tmp/",what,when,".xls")
     download.file(url,destfile)
}

例如:

> getIt("gas",2006)
trying URL 'http://oilandgas.ky.gov/Production%20Reports%20Library/2006%20-%20gas%20Production.xls'
Content type 'application/vnd.ms-excel' length 3490304 bytes (3.3 Mb)
opened URL
==================================================
downloaded 3.3 Mb

第一个除外:

> getIt("oil",2010)
trying URL 'http://oilandgas.ky.gov/Production%20Reports%20Library/2010%20-%20oil%20Production.xls'
Error in download.file(url, destfile) : 
  cannot open URL 'http://oilandgas.ky.gov/Production%20Reports%20Library/2010%20-%20oil%20Production.xls'
In addition: Warning message:
In download.file(url, destfile) :
  cannot open: HTTP status was '404 NOT FOUND'

虽然我可以得到 2010 年的汽油数据:

> getIt("gas",2010)
trying URL 'http://oilandgas.ky.gov/Production%20Reports%20Library/2010%20-%20gas%20Production.xls'
Content type 'application/vnd.ms-excel' length 4177408 bytes (4.0 Mb)
opened URL
==================================================
downloaded 4.0 Mb

所以看起来他们改变了那个链接的系统。您可以通过以下链接获取该数据,然后在粗糙的 Sharepoint HTML 中查找下载链接。

这就是我们讨厌 Sharepoint 的原因,孩子们。

【讨论】:

  • +1 我也讨厌它,sharepoint,但它无处不在 :) 你可以看到我的尝试,它甚至适用于你的第一个文件。再次抱歉之前没有展示我的尝试(技术原因)。
  • Argh 他们改为使用 xlsx 而不是 xls 作为第一个。
猜你喜欢
  • 2013-03-28
  • 1970-01-01
  • 2018-06-22
  • 2019-03-27
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多