使用 Python 2.7 的 HTML 解析树

2023-12-22

我试图为下面的 HTML 表配置一棵解析树,但无法形成它。我想看看树结构是什么样的!有人可以帮助我吗?

# <html>
#  <head>
#   <title>
#    The Dormouse's story
#   </title>
#  </head>
#  <body>
#   <p class="title">
#    <b>
#     The Dormouse's story
#    </b>
#   </p>
#   <p class="story">
#    Once upon a time there were three little sisters; and their names were
#    <a class="sister" href="http://example.com/elsie" id="link1">
#     Elsie
#    </a>
#    ,
#    <a class="sister" href="http://example.com/lacie" id="link2">
#     Lacie
#    </a>
#    and
#    <a class="sister" href="http://example.com/tillie" id="link2">
#     Tillie
#    </a>
#    ; and they lived at the bottom of a well.
#   </p>
#   <p class="story">
#    ...
#   </p>
#  </body>
# </html>

EDIT

Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\matt>easy_install ete2
Searching for ete2
Reading http://pypi.python.org/simple/ete2/
Reading http://ete.cgenomics.org
Reading http://ete.cgenomics.org/releases/ete2/
Reading http://ete.cgenomics.org/releases/ete2
Best match: ete2 2.1rev539
Downloading http://ete.cgenomics.org/releases/ete2/ete2-2.1rev539.tar.gz
Processing ete2-2.1rev539.tar.gz
Running ete2-2.1rev539\setup.py -q bdist_egg --dist-dir c:\users\arupra~1\appdat
a\local\temp\easy_install-sypg3x\ete2-2.1rev539\egg-dist-tmp-zemohm

Installing ETE (A python Environment for Tree Exploration).

Checking dependencies...
numpy cannot be found in your python installation.
Numpy is required for the ArrayTable and ClusterTree classes.
MySQLdb cannot be found in your python installation.
MySQLdb is required for the PhylomeDB access API.
PyQt4 cannot be found in your python installation.
PyQt4 is required for tree visualization and image rendering.
lxml cannot be found in your python installation.
lxml is required from Nexml and Phyloxml support.

However, you can still install ETE without such functionality.
Do you want to continue with the installation anyway? [y,n]y
Your installation ID is: d33ba3b425728e95c47cdd98acda202f
warning: no files found matching '*' under directory '.'
warning: no files found matching '*.*' under directory '.'
warning: manifest_maker: MANIFEST.in, line 4: path 'doc/ete_guide/' cannot end w
ith '/'

warning: manifest_maker: MANIFEST.in, line 5: path 'doc/' cannot end with '/'

warning: no previously-included files matching '*.pyc' found under directory '.'

zip_safe flag not set; analyzing archive contents...
Adding ete2 2.1rev539 to easy-install.pth file
Installing ete2 script to C:\Python27\Scripts

Installed c:\python27\lib\site-packages\ete2-2.1rev539-py2.7.egg
Processing dependencies for ete2
Finished processing dependencies for ete2

This answer comes a bit late, but still I'd like to share it: enter image description here

I used networkx http://networkx.github.com/documentation/latest/ and lxml http://lxml.de/(我发现它可以更优雅地遍历 DOM 树)。然而,树的布局取决于graphviz http://www.graphviz.org/ and pygraphviz http://networkx.lanl.gov/pygraphviz/安装。 networkx 本身只会以某种方式将节点分布在画布上。代码实际上比需要的要长,因为我自己绘制标签以将它们装箱(networkx 提供了绘制标签的功能,但它不会传递bboxmatplotlib 的关键字)。

import networkx as nx
from lxml import html
import matplotlib.pyplot as plt
from networkx.drawing.nx_agraph import graphviz_layout

raw = "...your raw html"

def traverse(parent, graph, labels):
    labels[parent] = parent.tag
    for node in parent.getchildren():
        graph.add_edge(parent, node)
        traverse(node, graph, labels)

G = nx.DiGraph()
labels = {}     # needed to map from node to tag
html_tag = html.document_fromstring(raw)
traverse(html_tag, G, labels)

pos = graphviz_layout(G, prog='dot')

label_props = {'size': 16,
               'color': 'black',
               'weight': 'bold',
               'horizontalalignment': 'center',
               'verticalalignment': 'center',
               'clip_on': True}
bbox_props = {'boxstyle': "round, pad=0.2",
              'fc': "grey",
              'ec': "b",
              'lw': 1.5}

nx.draw_networkx_edges(G, pos, arrows=True)
ax = plt.gca()

for node, label in labels.items():
        x, y = pos[node]
        ax.text(x, y, label,
                bbox=bbox_props,
                **label_props)

ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
plt.show()

如果您喜欢(或必须)使用 BeautifulSoup,请更改代码:

我不是专家...只是第一次查看 BS4,...但它有效:

#from lxml import html
from bs4 import BeautifulSoup
from bs4.element import NavigableString

...

def traverse(parent, graph, labels):
    labels[hash(parent)] = parent.name
    for node in parent.children:
        if isinstance(node, NavigableString):
            continue
        graph.add_edge(hash(parent), hash(node))
        traverse(node, graph, labels)

...

#html_tag = html.document_fromstring(raw)
soup = BeautifulSoup(raw)
html_tag = next(soup.children)

...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Python 2.7 的 HTML 解析树 的相关文章

  • goJS 下拉菜单删除项目

    我有简单的 python Flask goJS 图形应用程序 如下所示 节点和链接文本的源是从应用程序的后端加载的 我将它们设置为model modelData像这样的部分 var graphDataString JSON parse di
  • tkinter 上的“NoneType”对象没有属性“get”错误[重复]

    这个问题在这里已经有答案了 我最近开始使用 python 3 6 进行编码tkinter并尝试创建我自己的项目repl it 该项目是一个简单的交互式待办事项列表 但是我陷入困境并且无法使该功能正常工作 该函数只是简单地获取条目并将其添加到
  • Pyjnius导入jar文件

    Pyjnius 允许您为 java 类创建 python 包装器 例如 Hardware autoclass org myapp Hardware 有没有办法像这样导入现有的 jar 文件 语法是什么样的 您可以将 jar 添加到 CLAS
  • Pandas cut 方法不包括下限

    我正在尝试对包含 0 到 100 范围内的年龄的数据帧列进行分箱 当我尝试使用垃圾箱来包含零年龄时 它不起作用 这是一个使用包含我的数据范围的列表的演示 pd cut pd Series range 101 0 24 49 74 100 范
  • PRAW 出现 SSLError?

    我正在尝试开始使用 PRAW 但在使用 login 时遇到问题 我有以下代码 import praw r praw Reddit This is a test bot r login myRedditUsername password 我收
  • 确保特定列位于数据框中最后(或第一个)的最快方法是什么

    given df df pd DataFrame np arange 8 reshape 2 4 columns list abcd 假设我需要专栏 b 到最后 我可以做 df a c d b 但是确保给定列位于末尾的最有效方法是什么 这就
  • 如何在Python中重命名virtualenv?

    我拼错了名字virtualenv使用以下方法初始化它 virtualenv vnev 我实际上打算创建一个名为的环境venv 尝试重命名后vnev文件夹到venv 我发现这并没有提供太多帮助 激活环境的名称仍然重命名旧的vnev mv vn
  • Django 单元测试数据库没有被拆除?

    我编写了一些单元测试来测试我的 Django 应用程序 特别是一个测试套件中包含大量代码setUp 功能 所述代码的目的是为数据库创建测试数据 是的 我了解固定装置 并且选择在这种情况下不使用它们 当我运行单元测试套件时 运行的第一个测试通
  • Python textwrap.wrap 导致 \n 问题

    所以我只是重新格式化了一堆代码以合并textwrap wrap 却发现我所有的 n都消失了 这是一个例子 from textwrap import wrap def wrapAndPrint msg width 25 wrap msg to
  • Python 的二进制字符串列表

    我有一个像这样的二进制字符串 1100011101 我想将其解析为一个列表 其中每个 1 或 0 块都是列表中的单独值 例如 1100011101 变成 11 000 111 0 1 您可以通过使用正则表达式而不是从中获得一点 次要 性能g
  • Odoo:如何覆盖原始功能

    在 Odoo 中 每次打开产品表单时都会计算产品的数量 这发生在模型中product product gt function product available 该函数返回一个名为 res 的字典 Example res 8 qty ava
  • Python 日志记录 - 如何检查记录器是否为空

    我刚刚在我的应用程序中实现了日志记录 我想知道是否有一种方法可以检查记录器是否为空 我的想法是在我的脚本中设置两个处理程序 一个用于带水平仪的控制台WARNING 一个用于带级别的文件DEBUG 在脚本的最后 我需要检查是否CONSOLE记
  • 使用字体模块的 Tkinter 代码无法从命令行运行?

    我有使用 tkinter 的代码 我可以从 IDLE 运行得很好 但会引发异常AttributeError module object has no attribute font 当它从命令行运行时 其他 tkinter 程序工作正常 但任
  • Python 宏:用例?

    如果 Python 有一个类似于 Lisp Scheme 的宏工具 比如元Python https code google com p metapython 你会如何使用它 如果您是一名 Lisp Scheme 程序员 您会使用宏来做什么
  • 有什么理由不在Python中混合使用多处理和线程模块

    我正在考虑使用Python来实现一个需要大量多线程的程序 另一个要求是它将在桌面上运行 因此拥有许多进程将使应用程序显得混乱且难以杀死 在任务管理器中 因此 我正在考虑使用线程和多处理模块来减少进程数量 据我了解 GIL 仅适用于单个进程
  • Django - 从时间戳获取不同的日期

    我正在尝试按日期过滤用户 但直到我可以找到数据库中用户的第一个和最后一个日期为止 虽然我可以让我的脚本稍后过滤掉重复项 但我想从一开始就使用 Django 来完成此操作distinct因为它显着减少 我试过 User objects val
  • Python 多处理:全局对象未正确复制到子级

    前几天我回答了一个关于SO的问题 https stackoverflow com q 67047533 1925388关于并行读取 tar 文件 这是问题的要点 import bz2 import tarfile from multipro
  • 在 CSV 文件的最上面一行写入

    我有这个sample csv 文件 a 1 apple b 2 banana c 3 cranberry d 4 durian e 5 eggplant 并有以下代码 samplefile open sample csv rb rows s
  • Python 柯里化任意数量的变量

    我正在尝试使用柯里化在 Python 中进行简单的函数添加 我找到了这个咖喱装饰器here https gist github com JulienPalard 021f1c7332507d6a494b def curry func def
  • 编写 CherryPy 装饰器以进行授权

    我有一个cherrypy应用程序 在某些视图上我想开始只允许某些用户查看它们 并将其他任何人发送到需要授权的页面 有没有办法使用自定义装饰器来做到这一点 我认为这将是最优雅的选择 这是我想做的一个基本示例 class MyApp autho

随机推荐

  • 为什么 Magento 每个会话使用 2 个 cookie?

    出于数据安全和隐私原因 我想知道为什么 Magento 对一个前端会话使用两个 cookie 我所知道的是其中一个正在被设置Mage Core Model Cookie set 另一个在Zend Session expireSessionC
  • HTML & XHTML id 属性问题

    id 属性值可以以数字开头吗 对于 HTML 没有 http www w3 org TR html401 types html type name http www w3 org TR html401 types html type nam
  • 安卓中的人脸识别

    我需要在 Android 4 0 的应用程序中实现人脸识别登录 由于 Android Ice Cream Sandwich 中提供了人脸识别解锁功能 是否有任何开放的 SDK 或内置库来实现此功能 到目前为止 我遇到过外部 API 例如ht
  • Jenkins 管道 sh returnsstdout 不工作

    我正在尝试使用 Jenkins pipeline sh 命令的 returnStdout 功能 此处定义https jenkins io doc pipeline steps workflow durable task step code
  • JAR 文件:为什么提取然后压缩 JAR 文件会创建与原始大小不同的文件?

    我试图编辑提取的 Eclipse 插件 jar 文件中的单个字节 我注意到 在我将文件重新压缩为 jar 后 生成的文件比原始文件大 仅 1 并且该插件不起作用 Eclipse 已启动 但在选择工作区后静默关闭 回滚到原来的插件可以让它成功
  • 删除 index.php 并处理两个 Codeigniter 站点的子域(当其中一个站点位于另一个站点时)

    我有两个 Codeigniter 站点 一个位于另一个站点的子目录中 我需要一些帮助来修改我的 htaccess 文件以从两者中删除 index php 第一个站点 http subdomain domain com存储在 home sit
  • 将 2D 数组传递给 C++ 函数

    我有一个函数 我想将可变大小的二维数组作为参数 到目前为止我有这个 void myFunction double myArray myArray x y 5 etc 我在代码中的其他地方声明了一个数组 double anArray 10 1
  • 使用裁剪工具进行图像裁剪的 Django 应用程序

    我需要一个在客户端裁剪图像的应用程序 我的意思是 使用像 Jcrop jquery 插件这样的裁剪工具 我找到了这个工具 django 图像裁剪器 https github com marazmiki django image croppe
  • CUDA/PTX 32 位与 64 位

    CUDA 编译器可以选择生成 32 位或 64 位 PTX 这些有什么区别呢 是不是像 x86 一样 NVidia GPU 实际上也有 32 位和 64 位 ISA 还是仅与主机代码有关 指针肯定是最明显的区别 http docs nvid
  • NanoHTTPD - 将 https 流转换为 http

    为了克服 Chromecast 对来自自认证 https 服务器 在我的例子中是 Subsonic 音乐服务器 进行流传输的限制 我正在利用已经作为我的 Android 应用程序的一部分运行的 NanoHTTPD 服务器实例 这个想法是从
  • 如何在 Dart 中将 RxInt 转换为 Int ||扑?

    我正在玩扑扑 我遇到错误并且没有得到任何正确的解决方案 在我的应用程序中 我有一些可观察的变量GetX https pub dev packages get控制器 当尝试应用某种格式然后在此处获取日志时 Exception caught b
  • Maven 3.0.4 NoSuchMethod:... java.lang.NoSuchMethodError:com.google.common.collect.ImmutableSet.copyOf(..)

    我已经安装了Maven 3 0 4 with Homebrew每当我运行mvn命令我得到以下信息 Exception in thread main java lang NoSuchMethodError com google common
  • OkHttp 对请求启用/禁用 gzip 压缩

    我在用着Retrofit管理我的请求并希望进行一些测试来检查使用或不使用 gzip 的请求大小 默认情况下OkHttp对请求执行 gzip 压缩 或者必须使用拦截器 https github com square okhttp wiki I
  • jQuery 文档就绪与窗口加载冲突?

    我正在尝试拼凑一个视频库 我正在使用 jQuery 制作滑出面板 这很简单 我还使用 jQuery 来滚动缩略图 他们都工作得很好 问题是我需要滚动缩略图在滑出面板内工作 但事实并非如此 我认为这与文档准备好和窗口加载两个功能有关 我不确定
  • Ruby 中引发异常与抛出异常有什么区别?

    Ruby 有两种不同的异常机制 Throw Catch 和 Raise Rescue 为什么我们有两个 什么时候应该使用其中一种而不是另一种 raise fail rescue and ensure handle errors 也称为例外情
  • 如何以编程方式更新客户商店信用

    我正在使用 Magento 版本 1 9 1 1 我需要更新客户的商店信用余额 我知道可以在 Magento 管理界面中执行此操作 但就我而言 我需要向服务器发出 HTTP 请求 并且实际上执行与通过 Magento 管理界面执行的操作相同
  • 将brew安装的库包含到XCode中

    我正在尝试使用 Raylib 创建游戏 我想使用 XCode 因为我认为库管理会像 Windows 上的 Visual Studio 一样简单 我安装了这个库brew install raylib 现在我尝试运行这个从 Raylib 网站复
  • apollo graphql 响应数据中未显示“Extensions”字段

    这里有一个可重现的例子 https github com stonecold123 typegraphql test Run app js并在操场上导航http localhost 4000 graphql http localhost 4
  • VBA 中的编辑距离 [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我有包含数据的 Excel 工作表 我想获取它们之间的 Levenshtein 距离 我已经尝试导出为文
  • 使用 Python 2.7 的 HTML 解析树

    我试图为下面的 HTML 表配置一棵解析树 但无法形成它 我想看看树结构是什么样的 有人可以帮助我吗 p class title b The Dormouse s story b p p class story Once upon a ti