使用beautifulsouppython从表中获取更深层的值

2024-10-02 14:25:49 发布

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

嗨,伙计们,我想得到这个表中的价格值,我尝试了很多代码,但都没有得到。你知道吗

  <div class="row">
        <div class="col-xs-60 dephTableBuy">
            <table class="dephTableBuyTable">
                <thead>
                    <tr>
                        <td>M</td>
                        <td>F</td>
                    </tr>
                </thead>
                <tbody id="bidOrders-temp-inj">
                            <tr class="orderRow" amount="1.3" price="9000" total="12000">
                                <td class="amount forBuyFirstTH">1.34742743</td>
                                <td class="price forBuyLastTH"><span class='part1'>9290</span>.<span class='part2'>00</span> <span class="buyCircleAdv"></span></td>
                            </tr>
                            <tr class="orderRow" amount="0.2" price="9252.02" total="2466.10">
                                <td class="amount forBuyFirstTH">0.2</td>
                                <td class="price forBuyLastTH"><span class='part1'>9,252</span>.<span class='part2'>02</span> <span class="buyCircleAdv"></span></td>
                            </tr>

这是我的无用代码:

table = soup.find_all("table",{"class": "dephTableBuyTable"})

for item in table:
    print(item.contents[0].find_all("tr",{"class": "price"})[0].text)


Tags: 代码divtableamountpricetrclasstd
1条回答
网友
1楼 · 发布于 2024-10-02 14:25:49

在每个tr标记中有两个包含price的位置:price属性第二个td单元格

定位行:

tr = soup.find('table', {'class': 'dephTableBuyTable'}).find_all('tr', {'class': 'orderRow'})

要在tag属性中获取价格,只需使用row['price']

for row in tr:
    print(row['price'])

# 9000
# 9252.02

要获取td标记中的价格,可以使用find获取td单元格,然后使用text属性:

for row in tr:
    print(row.find('td', {'class': 'price'}).text)

# 9290.00 
# 9,252.02 

相关问题 更多 >