【问题标题】:Getting data from url and putting it into DataFrame从 url 获取数据并将其放入 DataFrame
【发布时间】:2019-07-10 07:19:54
【问题描述】:

大家好,我目前正在尝试从 url 获取一些数据,然后尝试预测该文章应该属于哪个类别。 到目前为止,我已经这样做了,但它有一个错误:

    info = pd.read_csv('labeled_urls.tsv',sep='\t',header=None)
    html, category = [], []
    for i in info.index:
        response = requests.get(info.iloc[i,0])
        soup = BeautifulSoup(response.text, 'html.parser')
        html.append([re.sub(r'<.*?>','', 
                      str(soup.findAll(['p','h1','\href="/avtorji/'])))])
        category.append(info.iloc[0,i])

    data = pd.DataFrame()
    data['html'] = html
    data['category'] = category

错误是这样的:

IndexError: 单个位置索引器超出范围。

有人可以帮帮我吗?

【问题讨论】:

    标签: python python-3.x pandas web-scraping


    【解决方案1】:

    您可以避免 iloc 调用并改用iterrows,我认为您将不得不使用loc 而不是iloc,因为您正在对索引进行操作,但在使用ilocloc循环通常效率不高。您可以尝试以下代码(插入等待时间):

    import time
    
    info = pd.read_csv('labeled_urls.tsv',sep='\t',header=None)
    html, category = [], []
    for i, row in info.iterrows():
        url= row.iloc[0]
        time.sleep(2.5)  # wait 2.5 seconds
        response = requests.get(url)  # you can use row[columnname] instead here as well (i only use iloc, because I don't know the column names)
        soup = BeautifulSoup(response.text, 'html.parser')
        html.append([re.sub(r'<.*?>','', 
                      str(soup.findAll(['p','h1','\href="/avtorji/'])))])
        # the following iloc was probably raising the error, because you access the ith column in the first row of your df
        # category.append(info.iloc[0,i])
        category.append(row.iloc[0])  # not sure which field you wanted to access here, you should also replace it by row['name']
    
    data = pd.DataFrame()
    data['html'] = html
    data['category'] = category
    

    如果您真的只需要循环中的 url,请替换:

    for i, row in info.iterrows():
        url= row.iloc[0]
    

    通过类似的方式:

    for url in info[put_the_name_of_the_url_column_here]: # or info.iloc[:,0] as proposed by serge
    

    【讨论】:

    • 我只是将 row[0] 和 row[1] 作为名称。谢谢您的回答。我猜它应该需要一段时间,因为它有 4000 行。根据您的说法,最少需要多长时间?
    • 我不知道,因为最长的时间将是requests.get 电话。也许一个小时?顺便提一句。如果你的 url 指向同一个服务器,你可能应该在两者之间增加一些等待时间,让它呼吸一些空气而不会被阻塞。
    • 是的,这一切都来自一台服务器。你能帮我做吗,因为我还不知道怎么做。我是这个有趣领域的新手。
    • 稍等,我补充一下。
    • 与往常一样:请确保您真的被允许抓取该网站。快乐刮!
    【解决方案2】:

    错误可能是由于将索引传递给iloc 引起的:loc 期望索引值和列名,而iloc 期望行和列的数字位置。此外,您已将category 的行和列位置与category.append(info.iloc[0,i]) 互换。所以你至少应该这样做:

    for i in range(len(info)):
        response = requests.get(info.iloc[i,0])
        ...
        category.append(info.iloc[i,0])
    

    但是当您尝试迭代数据框的第一列时,上面的代码不是 Pythonic。最好直接使用列:

    for url in info.loc[:, 0]:
        response = requests.get(url)
        ...
        category.append(url)
    

    【讨论】:

    • 我也会尝试这个,但首先我需要等待前一个完成。您认为有更优化的代码吗?
    • 由于您只使用 url,因此仅遍历这一列就足够了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 2020-02-09
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多