错误:
C:\ Python> python webscrape.py Traceback(最近一次调用最后一次): 文件“webscrape.py”,第23行,in 打印(“集线器:”+集线器) TypeError:必须是str,而不是list
代码:
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)
答案 0 :(得分: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))