python-3.7 - 如何在没有 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/标签代码的情况下打印所有内容。只需清除列中的文本。
解决方案
检查以下符合您要求的代码。顺便说一句,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))
推荐阅读
- laravel - Laravel 与刀片 - 多重继承
- google-bigquery - 访问 STRUCT 中的第 10 到第 70 个元素
- android - 如何在某些索引处用不同颜色标记水平 ProgressBar,就像 Android 中的 Youtube 视频黄色广告标记一样
- php - 我如何使用硒按条件执行我的代码?
- blockchain - 执行 main.go 时我得到未定义的 ethclient
- hyperledger-composer - Hyperledger Composer(游乐场)未连接到最后一个链码版本
- java - @Value 静态注解在 @PostConstruct 执行中为空
- javascript - 如何将函数从 vbscripts 转换为 javascript
- python - pyhon上的密码功能,使用while循环
- jenkins - 如何从 groovy map 脚本调用参数到 Jenkins Pipeline