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

时间:2017-06-15 21:52:05

标签: python beautifulsoup

嗨伙计们想在这张桌子上得到价格值我尝试了很多代码但是却无法获得。

  <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)

ty

1 个答案:

答案 0 :(得分:2)

每个 tr 标记中有两个包含价格的地方:价格属性第二个td单元格

找到行:

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

要获取代码属性中的价格,只需使用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