马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
大佬们,为啥抓取的内容可以打印出来,但是保存的话就是只是最后一页的内容,前面的内容保存不了啊
代码和图都发了
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[i] + '\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()
你这打开方式是w,而且还循环打开?
这样就会覆盖上一次写入的内容了
建议在main里打开,并将文件对象
当成参数传入
|