【问题标题】:how to extract specific csv from web page html containing multiple csv file links如何从包含多个csv文件链接的网页html中提取特定的csv
【发布时间】:2017-03-23 20:40:13
【问题描述】:

我需要从下面的 html 页面中提取 csv 文件,一旦我得到它,我就可以用它做一些事情。下面是从先前的作业中提取特定的 html 代码行的代码。网址是'https://vincentarelbundock.github.io/Rdatasets/datasets.html' 那是测试代码,因此它在找到该行时会暂时中断。 我的 csv 行的一部分是 href 是 csv/datasets/co2.csv (我认为是 unicode 类型)

如何打开 co2.csv? 对问题的任何格式问题感到抱歉。代码已经被编辑器切片了。

import urllib
url = 'https://vincentarelbundock.github.io/Rdatasets/datasets.html'
from BeautifulSoup import *

def scrapper(url,k):
    c=0
    html = urllib.urlopen(url).read() 
    soup = BeautifulSoup(html)
#.    Retrieve all of the anchor tags
    tags = soup('a')
    for tag in tags:
        y= (tag.get('href', None))
        #print ((y))
        if y == 'csv/datasets/co2.csv':
            print y
            break
        c= c+ 1

        if c is k:
            return y
            print(type(y))

for w in range(29):
    print(scrapper(url,w))

【问题讨论】:

  • 请改进您的问题:不清楚您是只想处理 single co2.csv 文件,还是要处理 all 链接在 html 页面上的 csv 文件。
  • 我只想要一个文件。 Co2.csv
  • 我想获取该文件并对其进行数据分析(线性回归)。

标签: python html csv parsing url


【解决方案1】:

您正在为循环的所有 30 次迭代重新下载和重新解析完整的 html 页面,只是为了获取下一个 csv 文件并查看它是否是您想要的。这非常效率低下,对服务器也不是很有礼貌。只需阅读 html 页面一次,然后使用循环遍历您已经必须检查的标签是否是您想要的标签!如果是这样,对它做点什么,并停止循环以避免不必要的进一步处理,因为你说你只需要一个特定的文件。

与您的问题相关的另一个问题是,在 html 文件中,csv href 是相对 url。因此,您必须在他们所在文档的基本 url 上加入他们。urlparse.urljoin() 就是这样做的。

与问题没有直接关系,但你也应该尝试清理你的代码;

  • 修正缩进(第 9 行的注释)
  • 选择更好的变量名; y/c/k/w 毫无意义。

结果如下:

import urllib
import urlparse

url = 'https://vincentarelbundock.github.io/Rdatasets/datasets.html'
from BeautifulSoup import *


def scraper(url):
    html = urllib.urlopen(url).read() 
    soup = BeautifulSoup(html)
    # Retrieve all of the anchor tags
    tags = soup('a')
    for tag in tags:
        href = (tag.get('href', None))
        if href.endswith("/co2.csv"):
            csv_url = urlparse.urljoin(url, href)
            # ... do something with the csv file....
            contents = urllib.urlopen(csv_url).read()
            print "csv file size=", len(contents)
            break   # we only needed this one file, so we end the loop.

scraper(url)

【讨论】:

  • 是的,我的代码是第一次粗略的尝试,用于与这个问题无关的另一个项目。我也会查找相关网址。
  • 那么请在未来尽量不要发布“与问题无关”的代码——我们为什么还要阅读它?而是发布相关代码
  • 好的,谢谢。但我很高兴你能理解我的问题。
猜你喜欢
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多