对python不熟悉,并且尝试对每15分钟刷新一次的表进行webscrape。获取关于需要字符串的错误

2024-04-26 11:45:38 发布

您现在位置:Python中文网/ 问答频道 /正文

错误:

C:\Python>;Python语言网络垃圾 回溯(最近一次呼叫): “文件”网络垃圾,第23行,在 打印(“集线器:”+集线器) 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)

Tags: fromimport网络htmlaspageall集线器
1条回答
网友
1楼 · 发布于 2024-04-26 11:45:38

必须用逗号分隔它们,而不是连接它们:

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)。你知道吗

注意:如果您使用的是python2,那么print语句中不需要括号。你知道吗

另一种方法是使用字符串格式:

print(“hubs: {hubs}”.format(hubs=hubs))

相关问题 更多 >