命令行下载jar包
pip install xxxxxx -i http://pypi.douban.com/simple --trusted-host pypi.douban.com 使用上面的命令下载wheel、lxml、twisted、pywin32、scrapy五个jar包,xxxxxx内填包名 命令行创建项目 scrapy startproject yc yc是项目名 创建py文件 scrapy genspider baidu www.baidu.com baidu是文件名 文件名后写网址 在项目中的settings.py文件里设置: ROBOTSTXT_OBEY = False 不遵从机器人协议
DOWNLOAD_DELAY = 3 下载延迟3秒,即下载时间最多不超过3秒 默认请求头
DEFAULT_REQUEST_HEADERS={ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language':'en', 'User-Agent':'Mozilla/5.0(Windows NT 6.2;WOW64)AppleWebKit/537.36(KHTML,like Gecko)Chrome/27.0.1453.94 Safari/537.36'#浏览器的类型,这一行的值要到浏览器里面找。Ctrl+Shift+I打开开发者工具->点击第一行的Network->点击Name下的一个文件名->点击Headers往下滑动即可找到 }
#管道优先级 ITEM_PIPELINES = { 'TXmovies.pipelines.TxmoviesPipeline': 300, }
run.py文件 from scrapy import cmdline #执行命令行 为什么要以空格分隔分割成列表来执行 cmdline.execute('scrapy crawl txms'.split())#'scrapy crawl txms'.split()输出成了列表 ['scrapy','crawl','txms']
pipelines.py文件 class TxmoviesPipeline(object): def process_item(self, item, spider): print(item) return item
txms.py文件 import scrapy # ..回退一层文件夹 from ..items import TxmoviesItem class TxmsSpider(scrapy.Spider): name = 'txms' allowed_domains = ['v.qq.com'] start_urls = [ 'https://v.qq.com/x/bu/pagesheet/list?append=1&channel=cartoon&iarea=1&listpage=2&offset=0&pagesize=30'] #位移 offset = 0 def parse(self, response): #定义数据结构 items = TxmoviesItem() #将页面解析数据放到列表,每个页面有多个这种div,解析完后就有多条,存到列表 lists = response.xpath('//div[@class="list_item"]')# response.xpath('//div[@class="list_item"]')是列表 #遍历列表将数据存到数据结构item for i in lists: #从每个div中提取电影名字 items['name'] = i.xpath('./a/@title').get() #xpath查找a链接下的标题信息 #从每个div中提取电影描述 items['description'] = i.xpath('./div/div/@title').get() #移交控制权给管道 yield items #若位移小于120 if self.offset < 120: #位移修改 self.offset += 30 url = 'https://v.qq.com/x/bu/pagesheet/list?append=1&channel=cartoon&iarea=1&listpage=2&offset={}&pagesize=30'.format( str(self.offset)) # .format(str(self.offset))填充内容到offset={} #url = 'https://v.qq.com/x/bu/pagesheet/list?append=1&channel=cartoon&iarea=1&listpage=2&offset={'+str(self.offset)+'}&pagesize=30' #回调parse函数 yield scrapy.Request(url=url, callback=self.parse)# callback