html = '''
<div class="container">
<h2>Countries & Capitals</h2>
<table class="two-column td-red">
<thead><tr><th>Country</th><th>Capital city</th></tr></thead><tbody>
<tr class="grey"><td>Afghanistan</td><td>Kabul</td></tr>
<tr><td>Albania</td><td>Tirana</td></tr>
</tbody>
</table>
</div>
有了这个HTML,我想具体解析国家名称和首都城市名称,并将它们放入字典中,这样我就可以
dict["Afghanistan] = 'Kabul'
我已经开始做了
soup = BeautifulSoup(open(filename), 'lxml')
countries = {}
# YOUR CODE HERE
table = soup.find_all('table')
for each in table:
if each.find('tr'):
continue
else:
print(each.prettify())
return countries
但因为是第一次使用,所以很混乱。你知道吗
如果“tr”元素有两个“td”子元素,则可以选择它们,因为您有数据:
输出:
解决方案适用于给定的html示例:
我跳过了
try, except
块中的任何错误情况。我建议你去看看美丽之声,它涵盖了一切。你知道吗这个怎么样:
输出:
相关问题 更多 >
编程相关推荐