【问题标题】:extracting data from an html table in <p> rather than <table>从 <p> 而不是 <table> 中的 html 表中提取数据
【发布时间】:2019-12-10 14:33:58
【问题描述】:

我一直在使用 pd.read_html 尝试从 url 中提取数据,但数据列在

标签而不是 .我可能在这里错过了一个简单的课程,但我不确定使用什么函数来获得好的结果(表格)而不是我得到的长字符串。任何建议,将不胜感激! 我使用了这两种方法并得到了相同的结果:

import requests import pandas as pd url ='http://www.linfo.org/acronym_list.html' dfs = pd.read_html(url, header =0) df = pd.concat(dfs) df

import pandas as pd
url ='http://www.linfo.org/acronym_list.html'
data = pd.read_html(url, header=0)
data[0]

输出[1]:

ABCDEFGHIJKLMNOPQRSTUVWXYZ A AMD Advanced Micro Devices API 应用程序编程接口 ARP 地址解析协议 ARPANET 高级研究计划局网络 AS 自治系统 ASCII 美国信息交换标准代码 AT&T 美国电话电报公司 ATA 先进技术附件 ATM 异步传输模式 B B 字节 BELUG Bellevue Linux 用户组 BGP 边界网关协议...

【问题讨论】:

  • 你期望的结果如何?
  • 我正在寻找一个表格的结果,就好像我为表格标签中的相同数据运行该脚本一样。我知道我可以将页面保存为 html 文件并编辑标签以使其正常工作,但我只是在寻找一种方法以供将来参考。
  • 我正在使用 BeautifulSoup 解析请求 html 每个标签 p 和 br ,最终结果是一个数据框...稍后您可以将其导出到下面的 excel 文件中

标签: python pandas dataframe import html-parsing


【解决方案1】:

我正在使用 BeautifulSoup 来解析请求 html 每个标签 p 和 br ,最终结果是一个数据框...稍后您可以将其导出到 excel 文件中...希望对您有所帮助

from bs4 import BeautifulSoup
import requests
import pandas as pd

result = requests.get('http://www.linfo.org/acronym_list.html')
c = result.content
soup = BeautifulSoup(c, "html.parser")
samples = soup.find_all("p")

rows_list = []

for row in samples:
    tagstrong = row.find_all("strong")
    for x in tagstrong:
        #print(x.get_text())
        tagbr = row.find_all("br")
        for y in tagbr:
            new_row = {'letter':x.get_text(), 'content':y.next}
            rows_list.append(new_row)

df1 = pd.DataFrame(rows_list)
print(df1.head(10))

这是结果:

【讨论】:

  • @jakeant2 我们在这里寻求帮助
猜你喜欢
  • 1970-01-01
  • 2012-10-19
  • 2012-08-01
  • 2015-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多