【问题标题】:(Python)- How to store text extracted from HTML table using BeautifulSoup in a structured python list(Python)- 如何将使用 BeautifulSoup 从 HTML 表中提取的文本存储在结构化的 Python 列表中
【发布时间】:2017-02-23 16:48:11
【问题描述】:

我使用 beautifulsoup 解析网页:

import requests
from bs4 import BeautifulSoup 
page = requests.get("webpage url")
soup = BeautifulSoup(page.content, 'html.parser')

我找到表格并打印文本

Ear_yield= soup.find(text="Earnings Yield").parent
print(Ear_yield.parent.text)

然后我得到表中单行的输出

Earnings Yield
0.01
-0.59
-0.33
-1.23
-0.11

我希望将此输出存储在一个列表中,以便我可以在 xls 上打印并对元素进行操作(例如 if (Earnings Yield [0] > Earnings Yield [1])。 所以我写:

import html2text
text1 = Ear_yield.parent.text
Ear_yield_text = html2text.html2text(pr1)

list_Ear_yield = []
for i in Ear_yield_text :
list_Ear_yield.append(i)

认为我的网络数据已进入列表。我打印第四项并检查:

print(list_Ear_yield[3])

我希望输出为-0.33,但我得到了

n

这意味着列表包含单个字符而不是完整的单词: 请让我知道我哪里做错了

【问题讨论】:

    标签: python-3.x beautifulsoup


    【解决方案1】:

    那是因为你的Ear_yield_text 是一个字符串而不是一个列表。假设文本有新行,您可以直接这样做:

    list_Ear_yield = Ear_yield_text.split('\n')
    

    现在如果你打印 list_Ear_yield 你会得到这个结果

    ['Earnings Yield', '0.01', '-0.59', '-0.33', '-1.23', '-0.11']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      相关资源
      最近更新 更多