[英]Accessing a dictionary with tag types in BeautifulSoup
对于正在解析并放入列表中的字典中的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>"])
如何将标签转换为字符串,以便可以将其作为字典键访问? 我尝试了上述方法,但它表示我要访问的不只一件事...
keys = tbl.find_all('th').string
根据文档,如果在汤中调用具有多个元素的字符串,则不会得到None。 您会收到密钥错误,因为字典是空的! 相反,
keys = list(map(lambda x: x.string, tbl.findall('th')))
和值相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.