gpt4 book ai didi

python - 将html数据解析成python列表进行操作

转载 作者:太空狗 更新时间:2023-10-30 02:47:01 24 4
gpt4 key购买 nike

我正在尝试阅读 html 网站并提取其数据。例如,我想阅读公司过去 5 年的 EPS(每股 yield )。基本上,我可以读入它并可以使用 BeautifulSoup 或 html2text 创建一个巨大的文本 block 。然后我想搜索文件——我一直在使用 re.search——但似乎无法让它正常工作。这是我要访问的行:

EPS(基本)\n13.4620.6226.6930.1732.81\n\n

所以我想创建一个名为 EPS = [13.46, 20.62, 26.69, 30.17, 32.81] 的列表。

感谢您的帮助。

from stripogram import html2text
from urllib import urlopen
import re
from BeautifulSoup import BeautifulSoup

ticker_symbol = 'goog'
url = 'http://www.marketwatch.com/investing/stock/'
full_url = url + ticker_symbol + '/financials' #build url

text_soup = BeautifulSoup(urlopen(full_url).read()) #read in

text_parts = text_soup.findAll(text=True)
text = ''.join(text_parts)

eps = re.search("EPS\s+(\d+)", text)
if eps is not None:
print eps.group(1)

最佳答案

使用正则表达式来解析 html 不是一个好习惯。使用 BeautifulSoup 解析器:找到包含 rowTitle 类和 EPS (Basic) 文本的单元格,然后使用 valueCell 迭代下一个兄弟单元 类:

from urllib import urlopen
from BeautifulSoup import BeautifulSoup

url = 'http://www.marketwatch.com/investing/stock/goog/financials'
text_soup = BeautifulSoup(urlopen(url).read()) #read in

titles = text_soup.findAll('td', {'class': 'rowTitle'})
for title in titles:
if 'EPS (Basic)' in title.text:
print [td.text for td in title.findNextSiblings(attrs={'class': 'valueCell'}) if td.text]

打印:

['13.46', '20.62', '26.69', '30.17', '32.81']

希望对您有所帮助。

关于python - 将html数据解析成python列表进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17709058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com