2017-05-01 22 views
0

錯誤:剛接觸python並試圖對每15分鐘刷新一次的表進行webscrape。得到一個錯誤約需要一個字符串

C:\的Python>蟒蛇webscrape.py 回溯(最近通話最後一個): 文件 「webscrape.py」 23行,在 打印(「樞紐:」 +集線器) 類型錯誤:必須海峽,就不一一列舉

代碼:

from urllib.request import urlopen as uReq 
from bs4 import BeautifulSoup as soup 

my_url = 'http://www.ercot.com/content/cdr/html/real_time_spp' 

# opening up connection, grabbing the web page 
uClient = uReq(my_url) 
page_html = uClient.read() 
uClient.close() 

# html parsing 
page_soup = soup(page_html, "html.parser") 

# grabs the market conditions 
intervals = page_soup.findAll("div",{"id":"today"}) 

for interval in intervals: 
    hubs = interval.table.tr.th["class"] 

    price_intervals = interval.findAll("td",{"class":"labelClassCenter"}) 
    all_prices = price_intervals[0].text 

    print ("hubs:" + hubs) 
    print ("all_prices:" + all_prices) 
+1

呀,誤差非常描述本身...樞紐是一個列表,所以你不能表現出來就像是內容....如果例如,你可以寫'print(「Hubs:」+ hubs [0])',你將得到一個結果......或者你可以使用'join',就像'print(「Hubs:」+ hubs.join (「,」))' – Hackerman

回答

1

你必須用逗號將它們分開,不將它們連接起來:

print("hubs:", hubs) 

你得到同樣的警告,因爲這:

>>> print("hi" + [1]) 
Traceback (most recent call last): 
    File "<pyshell#0>", line 1, in <module> 
    print("hi" + [1]) 
TypeError: must be str, not list 
>>> print("hi", [1]) 
hi [1] 

與您試圖來連接(或放在一起),字符串和列表中的加號。如果你想做到這一點,你必須做出列表中的字符串:

>>> print("hi" + str([1])) 
hi[1] 

如果您想通過逗號分隔值,做','.join(hubs)

注意:如果您使用的是Python 2,則不需要print語句中的圓括號。

另一種方式來做到這一點是與字符串格式化:

print(「hubs: {hubs}」.format(hubs=hubs)) 
+0

如果您使用的是python2而不是python3,那麼您也可能不想在print語句中使用括號。 –

+0

@DanielH由於他的打印語句中使用了括號,因此他使用python 3。 – rassar

+1

是的,但是從Python的新問題來看,這不是保證。當我第一次學習python(2)時,我經常意外地插入括號,因爲這是其他編程語言(以及Python中的大多數其他操作)的工作原理。 –

相關問題