我正在尝试抓取该网站(底部表)https://www.eia.gov/dnav/ng/hist/rngwhhdD.htm,到目前为止我已经获得了代码。我需要帮助来清理抓取的数据。 (我只需要文本并删除HTML代码/标签)
(下面的代码有效) (我正在Jupyter笔记本电脑中这样做)
我一直在尝试“ .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 /标记代码的内容。只需清除列中的文本即可。
答案 0 :(得分:1)
检查以下符合您要求的代码。顺便说一句,遇到困难时,您可以阅读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))