Python - 将 HTML 文件中的内容输出到电子表格

标签 python

下面的部分内容来自另一个示例。它经过一些修改,用于读取 HTML 文件,并将内容输出到电子表格中。

由于它只是一个本地文件,使用 Selenium 可能有点过头了,但我只是想通过这个示例来学习。

from selenium import webdriver
import lxml.html as LH
import lxml.html.clean as clean
import xlwt

book = xlwt.Workbook(encoding='utf-8', style_compression = 0)
sheet = book.add_sheet('SeaWeb', cell_overwrite_ok = True)

driver = webdriver.PhantomJS()
ignore_tags=('script','noscript','style')

results = []

driver.get("source_file.html")
content = driver.page_source
cleaner = clean.Cleaner()
content = cleaner.clean_html(content)
doc = LH.fromstring(content)

for elt in doc.iterdescendants():
    if elt.tag in ignore_tags: continue
    text = elt.text or ''                                 #question 1
    tail = elt.tail or ''                                 #question 1
    words = ''.join((text,tail)).strip()
    if words:                                   # extra question
        words = words.encode('utf-8')                     #question 2
        results.append(words)                             #question 3
        results.append('; ')                              #question 3

sheet.write (0, 0, results)

book.save("C:\\ source_output.xls")
  1. text=elt.text or ''tail=elt.tail or '' – 为什么 .text.tail 有文字吗?为什么 或 '' 部分在这里很重要?
  2. HTML 文件中的文本包含特殊字符,例如 °(温度度数) - .encode('utf-8') 并不能使其完美输出,不在 IDLE 或 Excel 电子表格中。还有什么选择?
  3. 是否可以将输出连接到字符串而不是列表中?现在要将其附加到列表中,我必须 .append 两次才能添加文本和 ;

最佳答案

elt 是一个 html 节点。它包含某些属性文本部分。 lxml 提供了通过使用 .text.tail 提取所有属性和文本的方法,具体取决于文本所在的位置。

<a attribute1='abc'> 
    some text     ----> .text gets this
    <p attributeP='def'> </p>
    some tail     ---> .tail gets this 
</a>

或''背后的想法是,如果在当前html节点中没有找到text/tail,则返回None。稍后当我们想要连接/追加 None 类型时,它会提示。因此,为了避免将来出现任何错误,如果文本/尾部为 None,则使用空字符串 ''

<小时/>

度数字符是一个单字符的unicode字符串,但是当您执行.encode('utf-8')时,它会变成2字节的utf-8字节字符串。这 2 个字节只不过是 °\xc3\x82\xc2\xb0。所以基本上你不需要对 ° 字符进行任何编码,Python 解释器会正确解释该编码。如果没有,请在 python 脚本之上提供正确的 shebang。检查PEP-0263

# -*- coding: UTF-8 -*-
<小时/>

是的,您也可以将输出连接到字符串中,只需使用+,因为字符串类型没有append,例如

results = ''
results = results + 'whatever you want to join'

您可以保留该列表并合并您的两行:

results.append(words + '; ')

注意:刚才我检查了 xlwt 文档,并且 sheet.write() 仅接受字符串。所以基本上你不能传递结果,一个列表类型。

关于Python - 将 HTML 文件中的内容输出到电子表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26114038/

相关文章:

python - 从 Python 中的字符串中删除特定字符

python - “gpiod”不是一个包

javascript - 如何将 Django 模板变量传递给 WebPack 模块

python - 无法理解 numpy 数组添加

python - PyQt5 ComboBox - 如何在不影响下拉列表的情况下设置 CurrentText 的颜色?

python - 将逻辑回归从 R 迁移到 rpy2

python - 在 python 中使用 readlines?第一次

python - 将 django 项目迁移到新服务器,并且另一个 django 项目的 postgresql 数据库已存在

python - 从数据、周期范围和聚合函数创建 Pandas TimeSeries

python - 从不同的类调用一个类中的函数