AINIDEREN 发表于 2020-4-1 18:57:29

爬虫保存内容丢失

大佬们,为啥抓取的内容可以打印出来,但是保存的话就是只是最后一页的内容,前面的内容保存不了啊
代码和图都发了




import requests
import bs4
import lxml
import time

headers = {"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.116 Safari/537.36",
         "Host":"quotes.toscrape.com"}

def open_url(url):
    res = requests.get(url, headers=headers)
    soup = bs4.BeautifulSoup(res.text, 'lxml')
    return soup
   
def find_quote(new_url):
   
    quotes =[]
    targets = open_url(new_url).find_all('div', class_='quote')


    for each in targets:
      quotes.append(each.span.text)

    result = []
    lengh = len(quotes)
    for i in range(lengh):
      result.append(quotes + '\n\n')

      
    return result
   
def down_load(quote):
    with open('quote.txt', 'w', encoding='utf-8') as f:
      for each in quote:
            print(each)
            f.write(each)
            time.sleep(0.1)
   
def main():
    url = "http://quotes.toscrape.com"
    page = 3
    for i in range(1, int(page) + 1):
      new_url = url + '/page/' + str(i) + '/'
      quote = find_quote(new_url)
      down_load(quote)
if __name__ == "__main__":
    main()
   

qiuyouzhi 发表于 2020-4-1 19:04:18

你这打开方式是w,而且还循环打开?
这样就会覆盖上一次写入的内容了
建议在main里打开,并将文件对象
当成参数传入

AINIDEREN 发表于 2020-4-1 19:37:11

qiuyouzhi 发表于 2020-4-1 19:04
你这打开方式是w,而且还循环打开?
这样就会覆盖上一次写入的内容了
建议在main里打开,并将文件对象


谢谢{:5_102:}

wp231957 发表于 2020-4-1 19:37:33

你要保存3个文件,就要准备三个不同的文件名
比如我有一次下载了10000+的图片,自然需要10000+的不同文件名
页: [1]
查看完整版本: 爬虫保存内容丢失