Yun*_*nti 25 python beautifulsoup
我不知道是否有这样的事情 - 但我正在努力做一个有序的字典理解.但它似乎没有用?
import requests
from bs4 import BeautifulSoup
from collections import OrderedDict
soup = BeautifulSoup(html, 'html.parser')
tables = soup.find_all('table')
t_data = OrderedDict()
rows = tables[1].find_all('tr')
t_data = {row.th.text: row.td.text for row in rows if row.td }
Run Code Online (Sandbox Code Playgroud)
它现在仍然是一个正常的字典理解(我也遗漏了对汤样板的通常要求).有任何想法吗?
Mor*_*app 56
你无法直接理解OrderedDict.但是,您可以在构造函数中使用生成器OrderedDict.
试试这个尺码:
import requests
from bs4 import BeautifulSoup
from collections import OrderedDict
soup = BeautifulSoup(html, 'html.parser')
tables = soup.find_all('table')
rows = tables[1].find_all('tr')
t_data = OrderedDict((row.th.text, row.td.text) for row in rows if row.td)
Run Code Online (Sandbox Code Playgroud)