scrapy_爬虫
命令行下载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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构