python - 使用 beautifulsoup 提取嵌套项目

标签 python python-2.7 beautifulsoup

这很可能是重复的。我读了很多表格相关的问题--like this one -- 尝试了解如何提取嵌套更深的网页内容。

无论如何,这是源代码:

<div class='event-details'>
    <div class='event-content'>
    <p style="text-align:center;">
        <span style="font-size:14px;">
            <span style="color:#800000;">TICKETS: ...<br></span>
        </span>
        <span style="font-size:14px;">
            <span style="color:#800000;">Front-of-House $35 ...<br></span>
        </span>
    </p>
    <p><span style="font-size:14px;">From My Generation ...</span></p>
    <p><span style="font-size:14px;">With note for note ...</span></p>
    <p><span style="font-size:14px;">The Who Show was cast ...</span></p>
    <p><span style="font-size:14px;">With excellent musicianship ...</span></p>
    <p><span style="font-size:14px;">http://www.thewhoshow.com</span></p>
    </div>
</div>

这就是让它变得困难的原因:我不想要票证信息,它位于我确实想要的段落文本之前,并且所有文本在某一时刻或另一时刻前面都有相同的 style标签。即:<span style="font-size:14px;">

我希望 BS 有一种方法可以捕获段落提供的独特功能 - 即 p标签后面紧跟着上面的跨度标签。请参阅:<p><span style="font-size:14px;">

这是我所做的:

desc_block = newsoup.find('div', {'class','event-details'}).find_all('p')
description = []
for desc in desc_block:
    desc_check = desc.get_text()
description.append(desc_check)
print description[2:]

问题有两个:一是我附加了我不想要的字符(例如 \n)和信息(门票信息);第二,我要附加它,因为我真正想做的是提取文本并将其作为 utf-8 字符串添加到空字符串中。谁能帮我解决第一个问题——即捕获无关的p我不想要的标签和信息?任何帮助将不胜感激。谢谢。

最佳答案

如果您使用 lxml 解析文档,您可以使用XPath expressions根据元素在树中的位置及其属性仅选择您关心的元素。

安装lxml ,执行任一操作

  • easy_install lxml
  • pip install lxml
  • 将其声明为 setup.py 中的包的依赖项
  • 或使用任何其他方式安装软件包

(假设您已经安装了BeautifulSoup)

示例

from BeautifulSoup import UnicodeDammit
from lxml import html


def decode_html(html_string):
    converted = UnicodeDammit(html_string, isHTML=True)
    if not converted.unicode:
        raise UnicodeDecodeError(
            "Failed to detect encoding, tried [%s]",
            ', '.join(converted.triedEncodings))
    # print converted.originalEncoding
    return converted.unicode


tag_soup = open('mess.html').read()

# Use BeautifulSoup's UnicodeDammit to detect and fix the encoding
decoded = decode_html(tag_soup)

# Use lxml's HTML parser (faster) to parse the document
root = html.fromstring(decoded)

spans = root.xpath("//span[@style='font-size:14px;']")
wanted_spans = spans[2:]

blocks = []
for span in wanted_spans:
    line = span.text.strip().replace('\n', '')
    blocks.append(line)

description = '\n'.join(blocks)
print description

此代码使用 lxml的快速 HTML 解析器来解析文档(对于您提供的代码片段工作得很好),但 BeautifulSoup 的编码检测首先猜测适当的字符集并解码文档。了解更多如何使用lxml使用 BeautifulSoup 解析器,请参阅 lxml docs on BeautifulSoup

跨度由 XPath 表达式 //span[@style='font-size:14px;'] 选择,这基本上意味着:“文档中具有属性 <span /> 且具有精确值 style 的任何 font-size:14px;

如果您想更具体地选择元素,您可以使用类似的表达式

//div[@class='event-details']//span[@style='font-size:14px;']

仅选择 div 下面的跨度(某处)与类event-details 。现在,这确实是要匹配的精确值 - 如果甚至有 ;样式值后面有missig,则不会匹配。 XPath 不了解 CSS,它是一种通用查询语言,用于遍历 XML 文档中的元素或属性。如果您的文档困惑,并且您需要考虑这一点,则需要使用类似 contains() 的内容。在您的 XPath 表达式中。

spans[2:]然后选择除前两个跨度之外的所有跨度,并且 strip().replace('\n', '')确保文本中没有空格。最后,我连接所有行以形成换行符分隔的描述 - 如果您甚至不需要单个换行符,只需使用 ' '.join(lines) 连接行即可。 .

有关 XPath 语法的更多信息,请参阅 XPath Syntax 等。 W3Schools Xpath Tutorial 中的页面.

要开始使用 XPath,在众多 XPath testers 之一中摆弄您的文档也非常有帮助。 。此外,Firefox 的 Firebug 插件或 Google Chrome 检查器允许您显示所选元素的(或者更确切地说,众多之一)XPath。

关于python - 使用 beautifulsoup 提取嵌套项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20336112/

相关文章:

python - 非常嘈杂信号的 Scipy FFT 频率分析

Python:编写大型文本文件的快速有效方法

python - 无法使用 bs4 收集 div 内的 href

python - 网页抓取谷歌财经

python-3.x - 使用 BeautifulSoup 从篮球引用中提取表格时出现问题

python - matplotlib:绘制看起来像 pyplot.arrow 的弯曲箭头?

python - 通过计算雅可比行列式有效地使用 PyTorch 的 autograd 与张量

带有 Pandas : How does one recover the non intersecting parts of two dataframes? 的 Python 2.7

python-2.7 - 从目录中读取图像并用空格分隔 python 传递每个图像

python - isalpha python 函数不会考虑空格