【问题标题】:Parse HTML table data to JSON and save to text file in Python 2.7在 Python 2.7 中将 HTML 表格数据解析为 JSON 并保存到文本文件
【发布时间】:2015-07-26 16:27:40
【问题描述】:

我正在尝试从 这个网页,链接到网页 http://www.disastercenter.com/crime/uscrime.htm

我可以把它变成文本文件。但我想得到 Json 格式的响应。我如何在 python 中做到这一点。

这是我的代码:

import urllib        
import re     

from bs4 import BeautifulSoup    
link = "http://www.disastercenter.com/crime/uscrime.htm"    
f = urllib.urlopen(link)    
myfile = f.read()    
soup = BeautifulSoup(myfile)    
soup1=soup.find('table', width="100%")    
soup3=str(soup1)    
result = re.sub("<.*?>", "", soup3)    
print(result)    
output=open("output.txt","w")    
output.write(result)    
output.close()    

【问题讨论】:

  • 您的结果与 json 相差甚远,您期望输出什么?
  • 将数据放入由lists/dicts/strs/numbers组成的有用Python数据结构中,然后使用json模块。

标签: python json python-2.7


【解决方案1】:

以下代码将从两个表中获取数据,并将其全部输出为json格式的字符串。


工作示例(Python 2.7.9):

from lxml import html
import requests
import re as regular_expression
import json

page = requests.get("http://www.disastercenter.com/crime/uscrime.htm")
tree = html.fromstring(page.text)

tables = [tree.xpath('//table/tbody/tr[2]/td/center/center/font/table/tbody'),
          tree.xpath('//table/tbody/tr[5]/td/center/center/font/table/tbody')]

tabs = []

for table in tables:
    tab = []
    for row in table:
        for col in row:
            var = col.text_content()
            var = var.strip().replace(" ", "")
            var = var.split('\n')
            if regular_expression.match('^\d{4}$', var[0].strip()):
                tab_row = {}
                tab_row["Year"] = var[0].strip()
                tab_row["Population"] = var[1].strip()
                tab_row["Total"] = var[2].strip()
                tab_row["Violent"] = var[3].strip()
                tab_row["Property"] = var[4].strip()
                tab_row["Murder"] = var[5].strip()
                tab_row["Forcible_Rape"] = var[6].strip()
                tab_row["Robbery"] = var[7].strip()
                tab_row["Aggravated_Assault"] = var[8].strip()
                tab_row["Burglary"] = var[9].strip()
                tab_row["Larceny_Theft"] = var[10].strip()
                tab_row["Vehicle_Theft"] = var[11].strip()
                tab.append(tab_row)
    tabs.append(tab)

json_data = json.dumps(tabs)

output = open("output.txt", "w")
output.write(json_data)
output.close()

【讨论】:

  • 在我的网页末尾有按名称和年份指向各个州的链接。如果我什至想要这些作为我的 JSON 文件中的链接,我该如何提取它?
【解决方案2】:

如果您可以使用requestslxml 模块,这可能就是您想要的。此处介绍的数据结构非常简单,请根据需要进行调整。

首先,从您请求的 URL 中获取响应并将结果解析为 HTML 树:

import requests        
from lxml import etree
import json

response = requests.get("http://www.disastercenter.com/crime/uscrime.htm")
tree = etree.HTML(response.text)

假设您要提取这两个表,请创建此 XPath 并解压缩结果。 totals 是“犯罪数量”,rates 是“每 10 万人的犯罪率”:

xpath = './/table[@width="100%"][@style="background-color: rgb(255, 255, 255);"]//tbody'
totals, rates = tree.findall(xpath)

提取原始数据(td.find('./') 表示第一个子项,无论它有什么标签)并清理字符串(r'' Python 2.x 需要原始字符串):

raw_data = []
for tbody in totals, rates:
    rows = []
    for tr in tbody.getchildren():
        row = []
        for td in tr.getchildren():
            child = td.find('./')
            if child is not None and child.tag != 'br':
                row.append(child.text.strip(r'\xa0').strip(r'\n').strip())
            else:
                row.append('')
        rows.append(row)
    raw_data.append(rows)

将前两行中的表头压缩在一起,然后删除多余的行,在切片表示法中被视为第 11 步和第 12 步:

data = {}
data['tags'] = [tag0 + tag1 for tag0, tag1 in zip(raw_data[0][0], raw_data[0][1])]

for raw in raw_data:
    del raw[::12]
    del raw[::11]

存储其余的原始数据并创建一个 JSON 文件(可选:separators=(',', ':') 消除空格):

data['totals'], data['rates'] = raw_data[0], raw_data[1]
with open('data.json', 'w') as f:
    json.dump(data, f, separators=(',', ':'))

【讨论】:

    猜你喜欢
    • 2017-10-10
    • 1970-01-01
    • 2020-04-15
    • 2017-05-04
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 2022-01-16
    相关资源
    最近更新 更多