繁体   English   中英

从BeautifulSoup.findAll创建行列表的更优雅的方法

[英]More elegant way to create a list of lines from BeautifulSoup.findAll

我正在使用BeautifulSoup编写Web解析器。 我创建了一个由bs.findAll(text=True)生成的行的列表,然后将行拆分为一行并在其中应用我的逻辑。 html_payload是任意网页。

到目前为止,我的代码可以工作,但是它不是很漂亮,让我认为必须有一种更好,更愚蠢的编写方式。

    data_to_parse = BeautifulSoup(html_payload)
    lines_to_parse = []

    d = data_to_parse.findAll(text=True)
    for line in d:
        for line2 in line.strip().split('\n'):
            if line2:
                lines_to_parse.append(line2)

    for line in lines_to_parse:
        pass # here's where I start analyzing results

有谁能提出解决这个问题的更好方法?

只需一次获取所有文本并将其分成几行:

data_to_parse = BeautifulSoup(html_payload)
for line in data_to_parse.get_text().split("\n"):
    pass  # ... do something

您可以使用列表理解:

lines_to_parse = [line2 for line in data_to_parse.findAll(text=True) for line2 in line.strip().split('\n') if line2]

或者,您实际上可以结合收集和分析步骤:

d = data_to_parse.findAll(text=True)
for line in d:
     for line2 in line.strip().split('\n'):
         if line2:
             # analyze here

或者,请记住,您并没有大量使用BeautifulSoupxmltodict可能会帮助您将数据收集到列表中,看看。

希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM