【问题标题】:lxml parser browsing directory for html fileslxml解析器浏览html文件的目录
【发布时间】:2023-03-03 12:30:01
【问题描述】:

我正在使用此代码:

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:\ABC")
    with stdout2file("Test123.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, 'ABC')]", 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()

我收到此错误消息:

C:\Users\Anaconda3\python.exe C:/Users/PycharmProjects/untitled/Versuch/lxmlparser.py
Traceback (most recent call last):
  File "C:/PycharmProjects/untitled/Versuch/lxmlparser.py", line 42, in <module>
    trade_spider()
  File "C:/6930p/PycharmProjects/untitled/Versuch/lxmlparser.py", line 33, in trade_spider
    xml = skip_to(file, "<?xml")
  File "C:/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:\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>

对于以下内容,我的目录由 5 个子文件夹组成,每个子文件夹最多包含 12 个填充 HTML 文件的子文件夹。 如果我将os.chdir(r"F:\ABC\201X\XXX") 设置为目录“201X”中的每个子文件夹,则代码可以完美运行。但是它会给我上面提到的错误消息如果: 1. 我设置了os.chdir as r"F:\ABC\2012\October(10 月是 2012 年子文件夹中 lxml 解析器正在解析的第一个子文件夹。(对于所有其他子文件夹,这非常有效!?) 2.如果我设置os.chdir as r"F:\ABC。因为我不想手动设置所有子文件夹,所以我最初的意图必须是自动解析 ABC 中的所有子文件夹。我想如果我使用for file in glob.iglob('**/*.html', recursive=True): 它会浏览包含在我的目录“ABC”中的所有子文件夹?

有人遇到过类似的问题吗?

【问题讨论】:

  • 试试,with open(fle,encoding="utf=8") as f
  • 再次非常感谢@PadraicCunningham!它在我的第一个子文件夹“October”以及用于解析所有包含子文件夹的子文件夹“2012”上完美运行。
  • 不用担心,您可以将其添加为关闭问题的答案。
  • 所以又是我....该代码非常适合我在“04_Independent....”中的第一个子文件夹“2012”以及它包含的所有子文件夹“十月、十一月、十二月”。但是,我在其他一些子文件夹上随机测试了代码,似乎它不适用于所有人。代码已执行,但之后不会停止运行。创建了一个 txt 输出文件,但它是空的....任何想法是什么导致了这个问题?除了 utf=8 编码,我没有对代码进行任何更改。我不明白,为什么它在某些子文件夹上工作,而在其他一些子文件夹上却不行?!
  • P.S.我使用我的 BS4 版本作为替代,它可以在所有子文件夹中正常工作,没有问题。但正如我在另一篇文章中提到的,BS4 在解析大量 HTML 文件时速度很慢。获得最终的 txt 输出文件需要很长时间......

标签: python-3.x directory pycharm lxml


【解决方案1】:

UnicodeDecodeError 的编码是通过将编码设置为 utf-8 进行排序的,代码卡在循环中的问题是因为并非所有文件都有@987654322 @,有的有&lt;html ...修改后的功能会解决问题,我还添加了一些调试,这样你就可以看到哪些文件没有数据。

import logging
import contextlib
logger = logging.getLogger(__file__)
logging.basicConfig(filename="debug.log")
logger.setLevel(logging.DEBUG)




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

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

def trade_spider():
    os.chdir(r"C:\Users\Independent Auditors Report")
    with stdout2file("auditfeesexpenses.txt"):
        for file in glob.iglob('./*.html'):
            xml = skip_to(file, ("<?xml","<html"))
            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
            else:
                logger.debug("Nothing found in file {}".format(file))

trade_spider()

【讨论】:

  • 完美!这已经解决了我的问题!我唯一改变的是 open(fle, encoding="utf=8") as f: 确保不再有 utf-8 编码,但其他一切都很好!
【解决方案2】:

好的,这是编码问题。当将 with open(fle) as f: 更改为 with open(fle,encoding="utf=8") as f 并因此使用 utf-8 编码时,它可以正常工作。

【讨论】:

  • 此外,如果不是每个文件都有“
  • 此外,如果您要搜索的标签有子标签,如 或其他任何内容,您需要将 print(fraction.text, end="|" "\n") 替换为 print(fraction.xpath(".//text()")[0], end="|" "\n") 以获取包括子标签在内的所有文本。
【解决方案3】:

最终代码:

import lxml.etree as et
import os
import glob
import logging
import contextlib

logger = logging.getLogger(__file__)
logging.basicConfig(filename="debug.log")
logger.setLevel(logging.DEBUG)


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


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


def trade_spider():
    os.chdir(r"F:\XYZ")
    with stdout2file("Test123.txt"):
        for file in glob.iglob('**/*.html'):                             
            xml = skip_to(file, ("<?xml", "<html"))
            tree = xml.getroot()
            nsmap = {"ix": tree.nsmap["ix"]}
            fractions = xml.xpath("//ix:nonNumeric[contains(@name, 'NAMEATTRIBUTE')]", namespaces=nsmap)
            for fraction in fractions:
                print(file.split(os.path.sep)[-1], end="| ")
                print(fraction.get("name"), end="| ")
                print(fraction.xpath(".//text()")[0], end="|" "\n")
                break
            else:
                logger.debug("Nothing found in file {}".format(file))            
trade_spider()

非常感谢@Padraic Cunningham!

【讨论】:

    【解决方案4】:

    嗯,当我在 python 2 中使用西里尔符号处理文件并在 python 3 中制作时,我遇到了这种错误。

    我可以看到你也有类似的 可能这会帮助你 在文件顶部输入

    #!/usr/bin/python
    
    # -*- coding: utf-8 -*-
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-13
      • 2012-06-10
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      相关资源
      最近更新 更多