python - Python 在循环期间停止创建新文件
问题描述
我对 Python 还很陌生,所以我可以使用一些帮助。我基本上是在为自己的个人需求构建一个小型网络抓取工具,一切都进行得很好,直到我想将抓取的数据写入自己的文件。给定一个包含 80 个 url 的列表,循环将停止创建新文件,但仍会继续收集数据。我已经通过将所有数据汇集到一个文件中来测试循环,这非常有效,但我确实需要创建单独的文件。该循环将创建 38 个单独的文件,而不是我需要的 80 个。谁能帮我弄清楚为什么?我的代码如下:
while i < len(urls_to_scrape):
with urllib.request.urlopen(urls_to_scrape[i]) as response:
html = response.read()
smashsoup = BeautifulSoup(html,'html.parser')
title = smashsoup.find('h1').get_text()
author = smashsoup.find('a', {'itemprop':'author'}).get_text();
complete_title = title +' By '+ author
filename = hashlib.md5(complete_title.encode('utf-8')).hexdigest() + ".txt"
imgname = hashlib.md5(complete_title.encode('utf-8')).hexdigest() + ".jpg"
short_desc = smashsoup.find('div', {'itemprop':'description'}).get_text();
try:
long_desc = smashsoup.find('div', {'id':'longDescription'}).get_text();
except:
long_desc = ""
cats = smashsoup.find('div', {'itemprop':'genre'})
category = ""
for cat in cats.find_all('a'):
category += cat.get_text() + " - "
img = smashsoup.find('img',{'itemprop':'image'})
source = img.get('src');
nsource = source.replace('-thumb','')
#compile everything into a single text document
fo = open(filename,'a')
fo.write(str(complete_title.encode('ascii','ignore'))+"\n\n")
fo.write(str(short_desc.encode('ascii','ignore'))+"\n\n")
fo.write(str(long_desc.encode('ascii','ignore'))+"\n\n")
fo.write(category+"\n\n")
fo.flush()
fo.close()
i += 1
解决方案
非常感谢@jbet。你的评论让我回去重新检查我正在抓取的页面。事实证明,网站上实际上有几个相同的条目,所以很明显,当我试图为每个条目创建一个单独的文件时,它是重复的,导致文件写入过程停止但循环继续。我的解决方案是在文件名被散列之前为文件名添加一个时间戳,现在所有条目都已创建。
推荐阅读
- github-actions - 用于显示过期包依赖项数量的 Github 操作
- react-native - 如何使用 react-navigation@3.x 禁用屏幕手势
- python - Python“冻结”Jupyter笔记本中的列表推导
- sql-server - Django 多表查询,排除条件基于一张表中的最大值。使用 SQL Server
- php - 以秒为单位获取时差
- mysql - 急切加载错误调用 Laravel 6 中未定义的方法语法问题
- python - 如何合并两个csv?
- python - 从 ESPN 幻想中抓取数据(表)
- python - 两天内使用 datetime.now() 的 UTC 转换
- android - 如何判断您的 Android 应用程序是否已获得 Google 批准并可以在 Google Play 上首次公开发布