微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 GLOB、BS4 从多个本地 .html 文件中提取元素并写入 CSV Excel

如何解决使用 GLOB、BS4 从多个本地 .html 文件中提取元素并写入 CSV Excel

我正在尝试从多个本地下载的 .HTML 文件提取标记间的单词并提取到 CSV。它在使用 print (title) 命令时显示标题”列表,但一旦我尝试导出到 CSV,它只显示一个条目。

import glob
import lxml
import csv
from bs4 import BeautifulSoup
    
path = "C:\\Users\\user1\\Downloads\\lksd\\"
for infile in glob.glob(os.path.join(path,"*.html")):
    markup = (infile)
    soup = BeautifulSoup(open(markup,"r").read(),'lxml')
    title = soup.find_all('title')
    title.append(title)
    print ([title])

with open('output2.csv','w') as myfile:
   writer = csv.writer(myfile)
   writer.writerows((title))

有什么建议吗?

解决方法

会发生什么?

您将循环中的 title 附加到自身:

title = soup.find_all('title')
title.append(title)

尝试在循环外定义一个空列表,并将您的 title 附加到此列表中。

...
titleList = []

for infile in glob.glob(os.path.join(path,"*.html")):
    markup = (infile)
    soup = BeautifulSoup(open(markup,"r").read(),'lxml')
    title = soup.find_all('title')
    titleList.append(title)
  
with open('output2.csv','w') as myfile:
   writer = csv.writer(myfile)
   writer.writerows((titleList))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。