【问题标题】:Using BeautifulSoup to Parse HTML Table Returns b' ' in Each Cell使用 BeautifulSoup 解析 HTML 表在每个单元格中返回 b' '
【发布时间】:2017-11-22 18:15:14
【问题描述】:

我正在尝试解析 HTML 表格并将其写入 CSV。我的代码有效,但它为表中具有值的每个单元格返回b'<value>',为表中为空的每个单元格返回b''。有谁知道为什么会这样?

不幸的是,有问题的 URL 无法通过公共互联网访问,但这是我的代码供我在没有它的情况下进行审查:

    from bs4 import BeautifulSoup
    import urllib
    import csv
    import time
    url = <not accessible over public internet>
    html = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(html, "html.parser")
    table = soup.select_one("table")
    headers = [th.text.encode("utf-8") for th in table.select("tr th")]
    with open("test_" + time.strftime("%Y%m%d_%H%M%S") + ".csv", "w") as f:
        wr = csv.writer(f)
        wr.writerow(headers)
        wr.writerows([[td.text.encode("utf-8") for td in row.find_all("td")] for row in table.select("tr + tr")])

最后,这是我正在谈论的输出的屏幕截图示例。 (原谅删掉敏感内容造成的丑陋。)

Example_Output

【问题讨论】:

    标签: python html csv parsing beautifulsoup


    【解决方案1】:

    对此进行编辑以仅允许其中包含文本的值; (下面的 if td.text 部分)。 (假设你不想要空值)

    wr.writerows([[td.text.encode("utf-8") for td in row.find_all("td") if td.text] for row in table.select("tr + tr")])
    

    更新: 修改打开csv命令为

    with open("test_" + time.strftime("%Y%m%d_%H%M%S") + ".csv", "w", encoding='utf-8') as f:
    

    然后从 csv 写入中删除编码

    wr.writerows([[td.text for td...............
    

    【讨论】:

    • 谢谢,这确实删除了所有空值,但非空值仍包含在 b'&lt;value&gt;' 中,而不仅仅是 &lt;value&gt;。请参阅我的“Example_Output”屏幕截图。
    • 这是字节文字,表示数据不是字符串(因为您将数据编码为 UTF-8。Python 在比较等中忽略了这一点,所以不用担心。如果你想要要删除它,请尝试上面添加的解决方案。
    • 太棒了!谢谢。
    【解决方案2】:

    b'' 不是字符串的一部分。它是字节文字表示的一部分,与字符串"foo"'foo' 完全相同,只有foo 是字符串,引号只是视觉表示的一部分。您可以使用 encodedecode 方法在 unicode 字符串和字节字符串之间进行转换。

    【讨论】:

      猜你喜欢
      • 2014-09-03
      • 2011-05-10
      • 2015-11-02
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 2019-08-12
      • 1970-01-01
      相关资源
      最近更新 更多