首页 > 解决方案 > 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

标签: python

解决方案


非常感谢@jbet。你的评论让我回去重新检查我正在抓取的页面。事实证明,网站上实际上有几个相同的条目,所以很明显,当我试图为每个条目创建一个单独的文件时,它是重复的,导致文件写入过程停止但循环继续。我的解决方案是在文件名被散列之前为文件名添加一个时间戳,现在所有条目都已创建。


推荐阅读