【问题标题】:scrape webpage and save as CSV with BS4 and Pandas使用 BS4 和 Pandas 抓取网页并保存为 CSV
【发布时间】:2016-11-10 13:58:36
【问题描述】:

当我抓取网页并将结果保存在 csv 文件中时,我通常会使用 R。 这在 R 中非常简单,但是由于 Raspbian 和其中一个包之间的一些不兼容,我的 R 代码在我的 Raspberry Pi 上不起作用。所以我决定尝试在 Python 中完成我的工作。

我想做的事情很简单:从本地新闻网页中抓取标题、链接和图片链接并保存为 csv。

当我在 Jupyter 笔记本(在 Windows 上)中尝试我的代码时一切正常,csv 文件有一个包含 12 行的漂亮数据框,但是当我在我的 Raspberry 上尝试我的代码时,csv 文件只包含一行。

这是我的第一个 python 代码,除了“many Hello world”,所以我知道它并不完美,但我完全不知道为什么它不能在 Raspberry 上运行

感谢您的帮助

# coding: utf-8
from bs4 import BeautifulSoup
import urllib
r = urllib.urlopen('http://krakow.tvp.pl/554275/aktualnosci').read()
soup = BeautifulSoup(r,'html.parser')
aktualnosci = soup.find_all("div", class_={"recommended","item hidden","image border-radius-5","meta cf","title"})
tytuly = soup.find_all("li", class_ = "border-radius-5")

prefix="http://krakow.tvp.pl"
link_aktualnosci = []
link_grafika_aktualnosci = []
link_tytul_aktualnosci = []
#course = []
temp = []
courses_list = []

for item in aktualnosci:
    temp1 = item.a['href'] # pobieram link do artykulu
    link_aktualnosci.append(temp1.encode('UTF-8'))
    
    temp2 = item.img.get('src') # pobieram link do grafiki
    link_grafika_aktualnosci.append(temp2.encode('UTF-8'))

    
    temp3 = item.find('span',class_="title").text.strip().encode('UTF-8') # pobieram tekst tytułu
    link_tytul_aktualnosci.append(temp3)
    
    temp = [temp1,temp2,temp3]
    courses_list.append(temp)

import pandas as pd

df = pd.DataFrame(courses_list)

df.to_csv('aktualnosci.csv')

【问题讨论】:

    标签: python csv pandas raspberry-pi


    【解决方案1】:

    我现在不能测试这个;我没有安装 Python。但是……这对你有用吗?

    import pandas as pd
    df = pd.read_html('http://krakow.tvp.pl/554275/aktualnosci', 
        header=0, 
        index_col=0)[2]
    print (df)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多