【发布时间】:2018-07-01 14:00:53
【问题描述】:
使用下面的代码,我想从 html 输出中返回一个 Python DataFrame。这是可以从 Python 中的包中完成的吗?表格格式见网页链接。
from bs4 import BeautifulSoup
import urllib.request
r = urllib.request.urlopen("https://www.zacks.com/zrank/sector-industry-classification.php").read()
soup = BeautifulSoup(r, "html.parser")
soup.find_all("script")[16]
输出脚本:
<script>window.app_data =
{
columns : [
{ "mDataProp" : "Sector Group"
, "sTitle" : "Sector Group"
, "sClass" : "alpha"
, "bSortable" : true
}
,
{
"mDataProp" : "Sector Code"
, "sTitle" : "Sector Code"
, "sClass" : ""
, "bSortable" : false
}
,
{
"mDataProp" : "Medium(M) Industry Group"
, "sTitle" : "Medium(M) Industry Group"
, "sClass" : "alpha"
, "bSortable" : false
}
数据包含以下内容:
data" : [ { "Sector Group" : "<span title=\"Index\" >Index</span>", "Sector Code" : "0", "Medium(M) Industry Group" : "<span title=\"Indices\" >Indices</span>", "Medium(M) Industry Code" : "0", "Expanded(X) Industry Group" : "<span title=\"Indicies\" >Indicies</span>", "Expanded(X) Industry Code" : "400" } , { "Sector Group" : "<span title=\"Consumer Staples\" >Consumer Staple...</span>", "Sector Code" : "1", "Medium(M) Industry Group" : "<span title=\"Food\" >Food</span>", "Medium(M) Industry Code" : "3", "Expanded(X) Industry Group" : "<span title=\"Food - Meat Products\" >Food - Meat Pro...</span>", "Expanded(X) Industry Code" : "75" } , { "Sector Group" : "<span title=\"Consumer Staples\" >Consumer Staple...</span>", "Sector Code" : "1", "Medium(M) Industry Group" : "<span title=\"Cons Prod-misc Staples\" >Cons Prod-misc...</span>", "Medium(M) Industry Code" : "7", "Expanded(X) Industry Group" : "<span title=\"Funeral Services\" >Funeral Service...</span>", "Expanded(X) Industry Code" : "78" } , { "Sector Group" : "<span title=\"Consumer Staples\" >Consumer Staple...</span>", "Sector Code" : "1", "Medium(M) Industry Group" : "<span title=\"Food\" >Food</span>", "Medium(M) Industry Code" : "3", "Expanded(X) Industry Group" : "<span title=\"Food - Confectionery\" >Food - Confecti...</span>", "Expanded(X) Industry Code" : "72" } , { "Sector Group"
注意:此处粘贴的数据过多。我也尝试了以下方法,因为其他答案提出了类似的方法,除了我选择了所有使用:
import re
pattern = re.compile("'.*': '.*'")
fields = dict(re.findall(pattern, soup))
print(fields)
输出为{}
【问题讨论】:
标签: python pandas beautifulsoup