使用beautifulGroup中的标记类型访问字典

2024-09-28 03:12:14 发布

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

对于被解析并放入列表中字典的HTML,我知道<th>Name</th>对应一个值。在

它似乎抛出了一个键错误,因为它是一个标记,而不是一个字符串。在

courseCode = "BSB119"

page = requests.get("https://www.qut.edu.au/study/unit?unitCode=" + courseCode)

soup = BeautifulSoup(page.content, 'html.parser')
tables = soup.find_all(class_='table assessment-item')

numOfTables = 0
list_ = []
dictionary_ = {}

for tbl in tables:
    numOfTables = numOfTables + 1
    keys = tbl.find_all('th').string
    values = tbl.find_all('td').string
    new_data = dict(zip(keys, values))
    list_.append(new_data)

for i in range(0,numOfTables):
    print(list_[i]["<th>Name</th>"])

如何将标记转换为字符串以便可以作为字典键访问它?我试过上面的方法,但上面说我访问的不止一件事。。。在


Tags: 字符串name标记fortables字典pageall
1条回答
网友
1楼 · 发布于 2024-09-28 03:12:14
keys = tbl.find_all('th').string

根据文档,如果用一个以上的元素调用soup上的string,则不会得到任何结果。因为dict是空的,所以你得到了一个keyerror!相反

^{pr2}$

值也是一样的

相关问题 更多 >

    热门问题