【问题标题】:Code transformation from BS4 to lxml parser从 BS4 到 lxml 解析器的代码转换
【发布时间】:2016-05-17 16:48:16
【问题描述】:

我正在做一个项目,使用 BS4 从本地存储的 HTML 文件中提取特定信息。因为我确实有大量文件(> 100 万)速度和性能是浏览所有文件的有用代码的关键。到目前为止,我一直在使用 BS4,就像我之前在网络爬虫上工作一样,我认为 BS4 非常简单方便。但是,如果涉及到大数据,BS4 就慢了一步。我读到了 lxml parser 和 html.parser ,这似乎是 Python 中用于 HTML 文档的最简单和最快的解析器。

所以我的代码现在看起来像:

from bs4 import BeautifulSoup
import glob
import os
import re
import contextlib


@contextlib.contextmanager
def stdout2file(fname):
    import sys
    f = open(fname, 'w')
    sys.stdout = f
    yield
    sys.stdout = sys.__stdout__
    f.close()


def trade_spider():
    os.chdir(r"C:\Users\XXX")
    with stdout2file("output.txt"):
        for file in glob.iglob('**/*.html', recursive=True):
            with open(file, encoding="utf8") as f:
                contents = f.read()
                soup = BeautifulSoup(contents, "html.parser")
                for item in soup.findAll("ix:nonfraction"):
                    if re.match(".*SearchTag", item['name']):
                        print(file.split(os.path.sep)[-1], end="| ")
                        print(item['name'], end="| ")
                        print(item.get_text())
                        break
trade_spider()

它打开一个文本文件,进入我的设置目录(os.chdir(..)),搜索所有以 .html 结尾的文件,读取内容,如果找到名称属性为“SearchTag”的标签,它会获取相关的HTML 文本并将其打印到我打开的文本文件中。一场比赛结束后有一个休息时间,它将继续下一场比赛。 所以我读到的是,BS4 在内存中完成了这一切,这显着增加了处理时间。

这就是为什么我想使用 lxml(首选)或 html.parser 来更改我的代码。

你们中的任何人都是天才,并且能够在不改变我最初的简单想法的情况下更改我的代码以使用 lxml 解析器吗?

任何帮助表示感谢,因为我完全被困住了......

更新:

import lxml.etree as et
import os
import glob

import contextlib


@contextlib.contextmanager
def stdout2file(fname):
    import sys
    f = open(fname, 'w')
    sys.stdout = f
    yield
    sys.stdout = sys.__stdout__
    f.close()


def skip_to(fle, line):
        with open(fle) as f:
            pos = 0
            cur_line = f.readline().strip()
            while not cur_line.startswith(line):
                pos = f.tell()
                cur_line = f.readline()
            f.seek(pos)
            return et.parse(f)


def trade_spider():
    os.chdir(r"F:\04_Independent Auditors Report")
    with stdout2file("auditfeesexpenses.txt"):
        for file in glob.iglob('**/*.html', recursive=True):
            xml = skip_to(file, "<?xml")
            tree = xml.getroot()
            nsmap = {"ix": tree.nsmap["ix"]}
            fractions = xml.xpath("//ix:nonFraction[contains(@name, 'AuditFeesExpenses')]", namespaces=nsmap)
            for fraction in fractions:
                print(file.split(os.path.sep)[-1], end="| ")
                print(fraction.get("name"), end="| ")
                print(fraction.text, end=" \n")
                break

trade_spider()

我收到此错误消息:

Traceback (most recent call last):
  File "C:/Users/6930p/PycharmProjects/untitled/Versuch/lxmlparser.py", line 43, in <module>
    trade_spider()
  File "C:/Users/6930p/PycharmProjects/untitled/Versuch/lxmlparser.py", line 33, in trade_spider
    xml = skip_to(file, "<?xml")
  File "C:/Users/6930p/PycharmProjects/untitled/Versuch/lxmlparser.py", line 26, in skip_to
    return et.parse(f)
  File "lxml.etree.pyx", line 3427, in lxml.etree.parse (src\lxml\lxml.etree.c:79720)
  File "parser.pxi", line 1803, in lxml.etree._parseDocument (src\lxml\lxml.etree.c:116182)
  File "parser.pxi", line 1823, in lxml.etree._parseFilelikeDocument (src\lxml\lxml.etree.c:116474)
  File "parser.pxi", line 1718, in lxml.etree._parseDocFromFilelike (src\lxml\lxml.etree.c:115235)
  File "parser.pxi", line 1139, in lxml.etree._BaseParser._parseDocFromFilelike (src\lxml\lxml.etree.c:110109)
  File "parser.pxi", line 573, in lxml.etree._ParserContext._handleParseResultDoc (src\lxml\lxml.etree.c:103323)
  File "parser.pxi", line 679, in lxml.etree._handleParseResult (src\lxml\lxml.etree.c:104936)
  File "lxml.etree.pyx", line 324, in lxml.etree._ExceptionContext._raise_if_stored (src\lxml\lxml.etree.c:10656)
  File "parser.pxi", line 362, in lxml.etree._FileReaderContext.copyToBuffer (src\lxml\lxml.etree.c:100828)
  File "C:\Users\6930p\Anaconda3\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 1789: character maps to <undefined>

【问题讨论】:

  • 使用 lxml 本身将是最快的方法,添加您的数据样本
  • @PadraicCunningham:用示例编辑了 OP。不过这只是很短的一段,原始的html文件最多包含3000行......
  • 你要解析什么?还有命名空间吗?
  • 我想用 nameattribute "...AuditFeesExpenses" 解析 3,4203,600
  • 你能添加包含命名空间定义的文件的开头吗?

标签: python-3.x beautifulsoup pycharm lxml


【解决方案1】:

根据pastebin中的html文件整理html需要做一些工作,下面会找到名称属性包含'AuditFeesExpenses'的nonFraction标签:

import lxml.etree as et

def skip_to(fle, line):
    with open(fle) as f:
        pos = 0
        cur_line = f.readline().strip()
        while not cur_line.startswith(line):
            pos = f.tell()
            cur_line = f.readline()
        f.seek(pos)
        return et.parse(f)

xml = skip_to("/home/padraic/Downloads/sample_html_file.html","<?xml")
tree = xml.getroot()
# one mapping is None ->  None: 'http://www.w3.org/1999/xhtml'
nsmap = {k: v for k, v in tree.nsmap.items() if k}

print(xml.xpath("//ix:nonFraction[contains(@name, 'AuditFeesExpenses')]", namespaces=nsmap))

输出:

[<Element {http://www.xbrl.org/2008/inlineXBRL}nonFraction at 0x7f5b9e91c560>, <Element {http://www.xbrl.org/2008/inlineXBRL}nonFraction at 0x7f5b9e91c5a8>]

拉取文本和名称:

fractions = xml.xpath("//ix:nonFraction[contains(@name, 'AuditFeesExpenses')]", namespaces=nsmap)

for fraction in fractions:
    print(fraction.get("name"))
    print(fraction.text)

这会给你:

ns19:AuditFeesExpenses
1,850
ns19:AuditFeesExpenses
2,400

另外,如果你只是使用 ix 命名空间,你可以直接拉取它

tree = xml.getroot()
nsmap = {"ix":tree.nsmap["ix"]}

fractions = xml.xpath("//ix:nonFraction[contains(@name, 'AuditFeesExpenses')]", namespaces=nsmap)

for fraction in fractions:
    print(fraction.get("name"))
    print(fraction.text)

完整的工作代码:

def trade_spider():
    os.chdir(r"C:\Users\Independent Auditors Report")
    with stdout2file("auditfeesexpenses.txt"):
        for file in glob.iglob('**/*.html', recursive=True):
            xml = skip_to(file, "<?xml")
            tree = xml.getroot()
            nsmap = {"ix": tree.nsmap["ix"]}
            fractions = xml.xpath("//ix:nonFraction[contains(@name, 'AuditFeesExpenses')]", namespaces=nsmap)
            for fraction in fractions:
                print(file.split(os.path.sep)[-1], end="| ")
                print(fraction.get("name"), end="| ")
                print(fraction.text, end="|")

代替 os.chdir 你还可以:

for file in glob.iglob('C:/Users/Independent Auditors Report/**/*.html', recursive=True):

【讨论】:

  • 完美!感谢您对此的帮助!我将在我的计算机上为几个示例运行此代码并为您提供反馈。只是一个问题,我如何将 os.chdir 运算符放入此代码中,因为我需要将原始目录路径粘贴到我的代码中以浏览整个目录及其子文件夹?
  • 保持你自己的逻辑,只需将文件传递给skip_to函数,lxml还有一些其他选项,但看看你如何使用上面的逻辑,我们可以从那里开始
  • 编辑 OP。如果我使用您的代码版本,它只使用 'xml = skip_to(...)' 运算符解析一个文件,它可以完美运行。但是当我试图插入我的 os.chdir 逻辑时,我没有让代码工作?
  • @FlorianSchramm,我回滚了你的编辑,但我会在几分钟内添加完整的工作代码
  • 好的,我会记住的。在我的BS4爬虫中我也使用了utf-8 encondig,不知道为什么我这次没有做...
猜你喜欢
  • 1970-01-01
  • 2019-02-27
  • 1970-01-01
  • 2013-02-24
  • 1970-01-01
  • 2012-01-18
  • 1970-01-01
  • 2018-10-07
  • 2011-07-11
相关资源
最近更新 更多