Skip to main content
 首页 » 编程设计

/tr>/td>"" rel="bookmark">python之用 python 的 BeautifulSoup 解析 "tbody>/tr>/td>"

2025年01月19日8虾米姐

我有以下 HTML 代码:

<tbody> 
  <tr> 
    <td><a href="/block_explorer/address/1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa">1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa</a></td> 
    <td><a href="/block_explorer/address/hash/62e907b15cbf27d5425399ebf6f0fb50ebb88f18/">62e907b15cbf27d5425399ebf6f0fb50ebb88f18</a></td> 
    <td class="num">66.6771<small class="b-blockExplorer__small">1246</small>&nbsp;BTC</td> 
    <td class="num">66.6771<small class="b-blockExplorer__small">1246</small>&nbsp;BTC</td> 
    <td class="num">1089</td> 
  </tr> 
  <tr> 
    <td><a href="/block_explorer/address/12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX">12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX</a></td> 
    <td><a href="/block_explorer/address/hash/119b098e2e980a229e139a9ed01a469e518e6f26/">119b098e2e980a229e139a9ed01a469e518e6f26</a></td> 
    <td class="num">50.0572<small class="b-blockExplorer__small">3154</small>&nbsp;BTC</td> 
    <td class="num">50.0572<small class="b-blockExplorer__small">3154</small>&nbsp;BTC</td> 
    <td class="num">55</td> 
  </tr> 
  <!--- SNIP ---> 
</tbody> 

我想解析它以获得如下内容:

1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa,62e907b15cbf27d5425399ebf6f0fb50ebb88f18,66.6771,66.6771 
12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX,119b098e2e980a229e139a9ed01a469e518e6f26,50.0572,50.0572 

尝试使用 BeautifulSoup:

soup.select('tbody > tr > td')[rowcount].get_text(strip=True) 

我只有拳头<td>*</td> 我做错了什么?

请您参考如下方法:

试试这个

for row in soup.select('tbody tr'): 
    row_text = [x.text for x in row.find_all('td')] 
    print(', '.join(row_text))  # You can save or print this string however you want. 

输出:

1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa, 62e907b15cbf27d5425399ebf6f0fb50ebb88f18, 66.67711246 BTC, 66.67711246 BTC, 1089 
12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX, 119b098e2e980a229e139a9ed01a469e518e6f26, 50.05723154 BTC, 50.05723154 BTC, 55