import requests from bs4 import BeautifulSoup import os import time import sys import io sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') #找到网址 def getDatas(): header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'} url="https://movie.douban.com/top250" # url="file:///E:/scrapy/2018-04-27/movie/movie.html" # 打开网页 res=requests.get(url,headers=header) # 转化格式 response=BeautifulSoup(res.text,'html.parser') # 找到想要数据的父元素 datas=response.find_all('div',{'class':'item'}) # print(datas) #创建存放数据的文件夹 folder_name="output" if not os.path.exists(folder_name): os.mkdir(folder_name) # 定义文件 current_time=time.strftime('%Y-%m-%d',time.localtime()) file_name="move"+current_time+".txt" # 文件路径 file_path=folder_name+"/"+file_name for item in datas: print(item) rank=item.find('div',{'class':'pic'}).find('em').get_text() title=item.find('div',{'class':'info'}).find('div',{'class':'hd'}).find('a').find('span',{'class':'title'}).get_text() picUrl=item.find('div',{'class':'pic'}).find('a').find('img').get('src') print(picUrl) # 保存数据为txt格式 try: with open(file_path,'a',encoding="utf-8") as fp: fp.write("排名:"+rank+' ') fp.write("标题:"+title+' ') fp.write("图片路径:"+picUrl+' ') except IOError as err: print('error'+str(err)) finally: fp.close() pass getDatas()
当然了 爬取过程中不免有各种各样的问题出现 我出现 408 错误;网上找到408 错误说是触发了反爬取;
header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'} url="https://movie.douban.com/top250" # url="file:///E:/scrapy/2018-04-27/movie/movie.html" # 打开网页 res=requests.get(url,headers=header)
就ok了