首页 > 解决方案 > 如何在没有 HTML/TAG 的情况下以文本形式清除我的数据?

问题描述

我正在尝试抓取这个网站(底部表格)https://www.eia.gov/dnav/ng/hist/rngwhhdD.htm,到目前为止我已经得到了代码。我需要帮助清理抓取的数据。(我只需要文本并删除 HTML 代码/标签)

(下面的代码有效)(我在 Jupyter notebook 中这样做)

我一直在尝试“.text”和“.strip”,但到目前为止还没有运气。

import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import csv


#open page and grab html
my_url = ('https://www.eia.gov/dnav/ng/hist/rngwhhdD.htm')
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close


#HTML parser
page_soup = soup(page_html, 'html.parser')


#Find table
soup = page_soup.findAll("td",{"class":{"B6","B3"}})

#Print table
print(soup)

我希望在没有 HTML/标签代码的情况下打印所有内容。只需清除列中的文本。

标签: python-3.7

解决方案


检查以下符合您要求的代码。顺便说一句,BeautifulSoup Document当您遇到问题时,您可以阅读并编写一些代码来测试您的想法。希望对你有帮助。

# There is no need to use alias here which maybe make confusion later, although you can do it
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

# open page and grab html
my_url = ('https://www.eia.gov/dnav/ng/hist/rngwhhdD.htm')
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

# HTML parser
page_soup = soup(page_html, 'html.parser')

table = []

# Find table
ele_table = page_soup.find("table", summary="Henry Hub Natural Gas Spot Price (Dollars per Million Btu)")
# traverse table
col_tag = 'th'
ele_rows = ele_table.find_all('tr', recursive=False)
for ele_row in ele_rows:
    row = []
    ele_cols = ele_row.find_all(col_tag, recursive=False)
    for ele_col in ele_cols:
        # use empty string for no data column
        content = ele_col.string.strip() if ele_col.string else ''
        row.append(content)
    col_tag = 'td'
    # just save row with data
    if any(row):
        table.append(row)

# print table
for row in table:
    print('\t'.join(row))


推荐阅读