【问题标题】:Loop through BeautifulSoup list and parse each to HTML tags and data problem遍历 BeautifulSoup 列表并解析每个 HTML 标签和数据问题
【发布时间】:2020-03-17 03:49:47
【问题描述】:

Python 3 程序员,BeautifulSoup 和 HTMLParser 的新手。我正在使用 BeautifulSoup 从 HTML 文件中获取所有定义列表数据,并尝试将 dt 数据和 dd 数据作为键值对存储到 python 字典中。我的 HTML 文件 (List_page.html) 是:

<!DOCTYPE html>
<html lang="en">
<head>STH here</head>
<body>
    <!--some irrelavent things here-->
    <dl class="key_value">
        <dt>Sine</dt>
        <dd>The ratio of the length of the opposite side to the length of the hypotenuse.</dd>
        <dt>Cosine</dt>
        <dd>The ratio of the length of the adjacent side to the length of the hypotenuse.</dd>
    </dl>
    <!--some irrelavent things here-->    
</body>
</html>

而当我的 Python 代码是:

from bs4 import BeautifulSoup
from html.parser import HTMLParser

dt = []
dd = []
dl = {}

class DTParser(HTMLParser):
    def handle_data(self, data):
        dt.append(data)

class DDParser(HTMLParser):
    def handle_data(self, data):
        dd.append(data)

html_page = open("List_page.html")
soup = BeautifulSoup(html_page, features="lxml")

dts = soup.select("dt")
parser = DTParser()

# Start of part 1:
parser.feed(str(dts[0]).replace('\n', ''))
parser.feed(str(dts[1]).replace('\n', ''))
# end of part 1

dds = soup.select("dd")
parser = DDParser()

# Start of part 2
parser.feed(str(dds[0]).replace('\n', ''))
parser.feed(str(dds[1]).replace('\n', ''))
# End of part 2

dl = dict(zip(dt, dd))
print(dl)

输出是:

这会按预期正确输出内容。但是,当我用 for 循环替换第 1 部分(或第 2 部分)时,它开始出错:

例如,代码:

# Similar change for part 2
for dt in dts:
    parser.feed(str(dts[0]).replace('\n', ''))

在这种情况下只告诉我余弦的定义,而不是正弦。有了 2 个项目,我可以在没有循环的情况下做到这一点。但是如果我有更多的物品怎么办?所以想知道一个正确的方法来做到这一点。谢谢。

【问题讨论】:

    标签: python-3.x beautifulsoup html-parsing


    【解决方案1】:

    每次迭代都使用dts[0] 获取 dts 的第一个元素,而不是使用循环更新索引。改成:

    for i in range(len(dts)):
        parser.feed(str(dts[i]).replace('\n', ''))
    

    for i in range(len(dds)):
        parser.feed(str(dds[i]).replace('\n', ''))
    

    【讨论】:

      猜你喜欢
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 2016-03-19
      • 1970-01-01
      • 2012-12-24
      • 2017-10-30
      相关资源
      最近更新 更多