首页 > 解决方案 > 使用 BeautifulSoup1 从 html 表中获取数据

问题描述

content = soup.find_all("div", id = "ctl00_ContentPlaceHolder1_ctl03_divHO")

for book in content:
  stock = book.find('I', {'class'= "Item_Price10"}).text
  print (stock)

我想通过找出 CONTENT 中的值来使用 BS4 来获取股票价格,但代码不能正常工作。请帮助我,提前谢谢你

标签: pythonpython-3.xbeautifulsoupjson.net

解决方案


该类Item_price10似乎是<td>标签的一部分,因此您可以尝试以下操作:

import requests
from bs4 import BeautifulSoup

req = requests.get("https://s.cafef.vn/Lich-su-giao-dich-FPT-1.chn")
soup = BeautifulSoup(req.content, "html.parser")

for div in soup.find_all("div", id = "ctl00_ContentPlaceHolder1_ctl03_divHO"):
    for tr in div.find_all('tr'):
        for td in tr.find_all('td', {'class': "Item_Price10"}):
            print(td.text)
        print()

这将显示以下内容:

95.70 
95.70 
3,325,700 
319,480,000,000 
1,243,600 
95.50 
97.00 
95.40 
0 
0 
0 

94.70 
94.70 
...

推荐阅读