[英]Convert html table to dictionary without losing structure
我是python(和編程)的新手,並且是第一次使用BeautifulSoup
。
我試圖找到最好的方法來解析html中的表的內容並將其轉換為字典-理想情況下以最不脆弱的方式進行。
這是我要解析的HTML的示例(我為要提取的文本添加了鍵值數字)。
<div class="tablename">
<table border="0" cellpadding="0" cellspacing="0" style="border: 1px solid #dddddd; border-collapse: collapse; font-family: Arial, Helvetica, sans-serif; font-size: 14px; margin: 0; padding: 0; width: 100%">
<thead>
<tr>
<th colspan="4" style="background-color: #000; border: 1px solid #616161; color: #ffffff; font-size: 14px; font-weight: bold; line-height: 20px; padding: 14px 20px 12px 20px; text-align: left">Some text not needed</th>
</tr>
</thead>
<tbody>
<tr>
<td style="width: 20px"> </td>
<td style="border-bottom: 1px solid #dddddd; color: #666666; font-size: 14px; line-height: 20px; padding: 11px 20px 10px 0; text-align: left; width: 42.5%; vertical-align: middle">Key 1</td>
<td style="border-bottom: 1px solid #dddddd; color: #000; font-size: 14px; line-height: 20px; padding: 11px 0 10px 0; text-align: left; vertical-align: middle">Value 1</td>
<td style="width: 20px"> </td>
</tr>
<tr>
<td> </td>
<td style="border-bottom: 1px solid #dddddd; color: #666666; font-size: 14px; line-height: 20px; padding: 11px 20px 10px 0; text-align: left; vertical-align: middle">Key 2</td>
<td style="border-bottom: 1px solid #dddddd; color: #000; font-size: 14px; line-height: 20px; padding: 11px 0 10px 0; text-align: left; vertical-align: middle">Value 2</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td style="border-bottom: 1px solid #dddddd; color: #666666; font-size: 14px; line-height: 20px; padding: 11px 20px 10px 0; text-align: left; vertical-align: middle">Key 3</td>
<td style="border-bottom: 1px solid #dddddd; color: #000; font-size: 14px; line-height: 20px; padding: 11px 0 10px 0; text-align: left; vertical-align: middle">Value 3</td>
<td> </td>
</tr>
<tr>
我正在使用的代碼:
import requests
from bs4 import BeautifulSoup
html = requests.get('https://examplewebaddress.com')
soup = BeautifulSoup(html.text)
print(soup.tbody.text)
然后,我可以遍歷soup.tbody.text
字符串並將其拆分為鍵值對。 但這似乎不是一個好方法,而且我似乎正在丟失表的結構,方法是將其轉換為字符串,然后再次將其構建為字典。
有沒有更直接的方法將使用BeautifulSoup
(或更合適的東西)解析成一個表,然后可以使用它呢?
想法是遍歷表行,並為每一行提取第二個和第三個單元格的文本,這些文本將表示鍵和將來字典的值:
soup = BeautifulSoup(html.text)
result = dict([[item.get_text(strip=True) for item in row.find_all('td')[1:3]]
for row in soup.select("div.tablename table tr")[1:]])
print result
對於提供的樣本數據,它打印:
{u'Key 1': u'Value 1', u'Key 2': u'Value 2', u'Key 3': u'Value 3'}
div.tablename table tr
是一個CSS選擇器 ,它將匹配以div
class="tablename"
div
table
元素下的所有tr
元素。 我們將對select
( [1:]
)的結果進行切片以跳過第一行標題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.