【发布时间】:2019-10-12 12:33:24
【问题描述】:
起初,我尝试只打开一个名为“index.html”的文件,对其进行解析并将其保存为 csv 文件。这是代码,它运行良好。 enter image description here
with open('/Users/kwon/Downloads/cnn/index.html') as html_file:
soup = BeautifulSoup(html_file, 'html.parser')
cnn_file = open('cnn2.csv', 'w')
cnn_writer = csv.writer(cnn_file)
cnn_writer.writerow(['filename','date','headline','text'])
filename = 'index000'
print(filename)
date = soup.find(class_='update-time').text
date = date.split(' ')[5]+' '+date.split(' ')[6]+' '+date.split(' ')[7]
print(date)
headline = soup.title.text
headline = headline.split('-')[0]
print(headline)
txt = soup.find(class_="zn zn-body-text zn-body zn--idx-0 zn--ordinary zn-has-multiple-containers zn-has-r'\d*'-containers").text
print(txt)
cnn_writer.writerow([filename, date, headline, txt])
cnn_file.close()
但我想为目录文件夹中的所有 html 文件(index.html~index591.html)迭代相同的过程。所以我开始使用 glob 模块按顺序打开文件。然后,尝试像以前一样解析“for循环”。不知何故,我不知道如何按顺序读取和解析它们并将文件名命名为“index000”到“index591”。此外,如果我运行下面的代码,我会收到错误消息“find() 不接受关键字参数”。
import glob
path = '/Users/kwon-yejin/Downloads/cnn2/*.html'
files=glob.glob(path)
for file in files:
html = open(file, 'r')
soup = bs4.BeautifulSoup(html, 'html.parser')
for line in soup:
filename = 'index000'
print(filename)
date = line.find(class_='update-time').text
date = date.split(' ')[5]+' '+date.split(' ')[6]+' '+date.split(' ')[7]
print(date)
headline = line.title.text
headline = headline.split('-')[0]
print(headline)
txt = line.find(class_="zn zn-body-text zn-body zn--idx-0 zn--ordinary zn-has-multiple-containers zn-has-21-containers").text
print(txt)
【问题讨论】:
-
filename 是一个字符串,因此请使用字符串函数,例如
"index{:03}".format(number)- pyformat.info 。并使用for number, file in enumerate(files): -
也许你应该只使用一个
for-loop` 而不要使用for line in soup -
也许您将普通字符串分配给
line而string.find()不使用class_ -
感谢 cmets。我会按照你的建议修复它。
标签: python csv beautifulsoup