BeautifulSoup:如何提取封装在多个div/span/id标记中的文本

2024-09-28 01:33:34 发布

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

我需要提取数字(0.04)在“td”标签在这个html页面的结尾。你知道吗

      <div class="boxContentInner">
         <table class="values non-zebra">
   <thead>
   <tr>
      <th>Apertura</th>
      <th>Max</th>
      <th>Min</th>
      <th>Variazione giornaliera</th>
      <th class="last">Variazione %</th>
   </tr>
   </thead>
   <tbody>
   <tr>
      <td id="open" class="quaternary-header">2708.46</td>
      <td id="high" class="quaternary-header">2710.20</td>
      <td id="low" class="quaternary-header">2705.66</td>
      <td id="change" class="quaternary-header changeUp">0.99</td>
      <td id="percentageChange" class="quaternary-header last changeUp">0.04</td>
   </tr>
   </tbody>
</table>

      </div>

我在Python 2.8中使用BeautifulSoup尝试了以下代码:


from bs4 import BeautifulSoup 
import requests 

page= requests.get('https://www.ig.com/au/indices/markets-indices/us-spx-500').text 
soup = BeautifulSoup(page, 'lxml') 

percent= soup.find('td',{'id':'percentageChange'}) 
percent2=percent.text


print percent2


结果是没有。你知道吗

错误在哪里?你知道吗


Tags: dividtabletrclasstdheaderlast
1条回答
网友
1楼 · 发布于 2024-09-28 01:33:34

我看了一下https://www.ig.com/au/indices/markets-indices/us-spx-500,似乎您在执行percent= soup.find('td', {'id':'percentageChange'})时没有搜索正确的id

实际值位于<span data-field="CPC">VALUE</span>

enter image description here

您可以通过以下方式检索此信息:

percent = soup.find("span", {'data-field': 'CPC'})
print(percent.text.strip())

相关问题 更多 >

    热门问题