在html枚举之后为属性赋值

2024-09-30 18:23:34 发布

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

我正在寻找一种在html string上执行enumerate之后将属性分配给类对象的方法。基本上,这就是我所拥有的:

for j, td in enumerate(tr.select('td')):
   print(j, td.text)

这将输出:

0 UNITY
1 Unity Foods Limited
2 13.29
3 13.82
4  0.53
5  3.99%
6 0.12%
7 1.81
8 12,472,000
9 163
10 7,519

我要将这些值赋给以下类中的所有参数:

class Product:
    def __init__(self,
                 symbol,
                 name,
                 ldcp,
                 current,
                 change,
                 change_percent,
                 index_wt,
                 index_point,
                 volume,
                 free_float,
                 market_cap):
        self.symbol = symbol
        self.name = name
        self.ldcp = ldcp
        self.current = current
        self.change = change
        self.change_percent = change_percent
        self.index_wt = index_wt
        self.index_point = index_point
        self.volume = volume
        self.free_float = free_float
        self.market_cap = market_cap

有什么办法解决这个问题吗


Tags: nameselffreeindexcurrentfloatsymbolchange
1条回答
网友
1楼 · 发布于 2024-09-30 18:23:34

将值收集到一个列表中,并使用参数解包传递它们:

attributes = [td.text for td in tr.select('td')]
product = Product(*attributes)

请注意,只有当HTML包含的属性按照Product.__init__()定义中列出的顺序排列时,这种方法才有效

如果要忽略某些元素,可以在列表中应用筛选,例如:

attributes = [td.text for td in tr.select('td') if td.text != '']
product = Product(*attributes)

相关问题 更多 >