' INT'对象不可订阅(从网站上刮表)

时间:2018-01-10 05:16:03

标签: python pandas beautifulsoup typeerror

我对编码感到痛苦......我刚刚在大约一周前学会了如何使用终端,如果这让你知道我是多么的愚蠢。我需要学习如何从网站上抓取数据,以便我在我熟悉的网站上练习,并且我尝试创建一个显示此网址数据的csv文件:http://phish.net/song。我基本上修改了这个网站的代码(https://chihacknight.org/blog/2014/11/26/an-intro-to-web-scraping-with-python.html),我试图使用它。

from bs4 import BeautifulSoup
import requests
import pandas as pd
url = "http://phish.net/song?"
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data, "lxml")
table = soup.find('table')
rows = table.find('tr')
data = {
'song': [],
'original_artist': [],
'times': [],
'debut': [],
'last': [],
'gap': []
}
for row in rows:
    cols = row.find('td')
    data['song'].append(cols[0].get_text()))
    data['original_artist'].append(cols[1].get_text())
    data['times'].append(cols[2].get_text())
    data['debut'].append(cols[3].get_text())
    data['last'].append(cols[4].get_text())
    data['gap'].append(cols[5].get_text())
phishData = pd.DataFrame(data)
phishData.to_csv("PhishData.csv")

我收到以下错误:

Traceback (most recent call last):
  File "phishnet.py", line 20, in <module>
    data['song'].append(str(cols[0].get_text()))
TypeError: 'int' object is not subscriptable

哪个对象是不可订阅的?我该如何解决这个问题?在此先感谢您的帮助,请告诉我这是否适合使用此论坛。

1 个答案:

答案 0 :(得分:0)

pd.read_html似乎做你想做的事。

df = pd.read_html("http://phish.net/song?")[0]

df.head()
          Song Name Original Artist                 Times       Debut  \
0      Alumni Blues           Phish                   107  1985-03-16   
1     And So To Bed           Phish  Found in Discography         NaN   
2  You Enjoy Myself           Phish                   581  1986-02-03   
3         AC/DC Bag           Phish                   310  1986-04-01   
4    F**k Your Face           Phish                    13  1987-04-29   

         Last   Gap  
0  2017-07-29  13.0  
1         NaN   NaN  
2  2017-12-31   0.0  
3  2017-12-28   3.0  
4  2017-08-05   8.0 

最后to_csv来电 -

df.to_csv("PhishData.csv")