python3+scrapy+selenium爬取英雄联盟英雄资料
继前一篇文章用nodejs+puppeteer+chromium爬取了这个英雄资料后,在本篇同样爬这个页面,思路都差不多,只是用不同语言来实现,可作为参考,个人觉得爬虫还是nodejs比较好用,可能是我python太菜吧
本例环境和所需第三方包:python3、pycharm、selenium2.48.0(用3.0+版本会报错,因为新版本放弃phantomjs了,当然也可以用chrome和firefox,不过可能需要另外装驱动)、scrapy1.6.0
对于还没了解过scrapy和phantomjs的可以先看下这两篇博客,写的很详细:
https://www.cnblogs.com/kongzhagen/p/6549053.html
https://jiayi.space/post/scrapy-phantomjs-seleniumdong-tai-pa-chong
安装就不多说了,可以先装scrapy,如果有报错需要什么再装什么,一般windos还需要安装一个pywin32
创建项目:
scrapy startproject loldocument
cd loldocument
scrapy genspider hero lol.qq.com/data/info-heros.shtml
然后生成目录:
spiders/hero.py发起列英雄表页的请求获取每个英雄所对应的详情页url,循环访问每个url,然后得到想要的数据:
# -*- coding: utf-8 -*-
import scrapy
from loldocument.items import LoldocumentItem
import os
import urllib.request
import re
class HeroSpider(scrapy.Spider):name = 'hero'allowed_domains = ['lol.qq.com']start_urls = ['https://lol.qq.com/data/info-heros.shtml']def parse(self, response):heros = response.xpath('//ul[@id="jSearchHeroDiv"]/li')# heros = [heros[0], heros[1]]for hero in heros: # 遍历每个liimgu = 'http:' + hero.xpath("./a/img/@src").extract_first()title = hero.xpath("./a/@title").extract_first()headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0'}req = urllib.request.Request(url=imgu, headers=headers)res = urllib.request.urlopen(req)path = r'F:\loldocument\hero_logo' # 保存英雄头像的路径if not os.path.exists(path):os.makedirs(path)file_name = os.path.join(r'F:\loldocument\hero_logo', title + '.jpg')with open(file_name, 'wb') as fp:fp.write(res.read())url = 'https://lol.qq.com/data/' + hero.xpath("./a/@href").extract_first()request = scrapy.Request(url=url, callback=self.parse_detail)request.meta['PhantomJS'] = Truerequest.meta['title'] = titleyield requestdef parse_detail(self, response):# 英雄详情item = LoldocumentItem()item['title'] = response.meta['title']item['DATAname'] = response.xpath('//h1[@id="DATAname"]/text()').extract_first()item['DATAtitle'] = response.xpath('//h2[@id="DATAtitle"]/text()').extract_first()item['DATAtags'] = response.xpath('//div[@id="DATAtags"]/span/text()').extract()infokeys = response.xpath('//dl[@id="DATAinfo"]/dt/text()').extract()infovalues = response.xpath('//dl[@id="DATAinfo"]/dd/i/@style').extract()item['DATAinfo'] = {} # 英雄属性for i,v in enumerate(infokeys):item['DATAinfo'][v] = re.sub(r'width:', "", infovalues[i])yield item
items.py定义要存入item的字段:
# -*- coding: utf-8 -*-# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapyclass LoldocumentItem(scrapy.Item):# define the fields for your item here like:# name = scrapy.Field()title = scrapy.Field()DATAname = scrapy.Field()DATAtitle = scrapy.Field()DATAtags = scrapy.Field()DATAinfo = scrapy.Field()
因为用selenium爬取异步数据所以需要另外单独定义一个下载器中间件,在新建目录和文件,在/loldocument新建python package middlware.py:
from selenium import webdriver
from scrapy.http import HtmlResponse
import timeclass JavaScriptMiddleware(object):def process_request(self, request, spider):print("PhantomJS is starting...")driver = webdriver.PhantomJS() # 指定使用的浏览器# driver = webdriver.Firefox()driver.get(request.url)time.sleep(1)if 'PhantomJS' in request.meta :js = "var q=document.documentElement.scrollTop=1000"driver.execute_script(js) # 可执行js,模仿用户操作。此处为将页面拉至最底端。time.sleep(1)body = driver.page_sourceprint("访问详情页" + request.url)return HtmlResponse(driver.current_url, body=body, encoding='utf-8', request=request)else:js = "var q=document.documentElement.scrollTop=1000"driver.execute_script(js) # 可执行js,模仿用户操作。此处为将页面拉至最底端。time.sleep(1)body = driver.page_sourceprint("访问:" + request.url)return HtmlResponse(driver.current_url, body=body, encoding='utf-8', request=request)
settings.py修改三个配置:
ROBOTSTXT_OBEY = FalseDOWNLOADER_MIDDLEWARES = {'loldocument.middlewares.middleware.JavaScriptMiddleware': 543, #键为中间件类的路径,值为中间件的顺序'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware':None, #禁止内置的中间件
}ITEM_PIPELINES = {'loldocument.pipelines.LoldocumentPipeline': 100,
}
数据处理pipelines.py:
# -*- coding: utf-8 -*-# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import jsonclass LoldocumentPipeline(object):def process_item(self, item, spider):with open('hero_detail.txt', 'a') as txt:str = json.dumps(dict(item), ensure_ascii=False)txt.write(str)
执行 scrapy crawl hero 执行程序,同时命令窗会输出详情及异常信息,加--nolog可以不输出详情
得到的数据hero_detail.txt和英雄头像hero_logo目录:
python3+scrapy+selenium爬取英雄联盟英雄资料相关推荐
- scrapy框架爬取王者荣耀英雄数据
scrapy框架爬取王者荣耀英雄属性 爬虫工程 爬虫文件 import scrapy from theKingPro.items import ThekingproItemclass ThekingS ...
- 使用scrapy +selenium爬取动态渲染的页面
背景 在通过scrapy框架进行某些网站数据爬取的时候,往往会碰到页面动态数据加载的情况发生,如果直接使用scrapy对其url发请求,是绝对获取不到那部分动态加载出来的数据值.但是通过观察我们会发现 ...
- scrapy+selenium爬取五个外国新闻网站关于“中国“的新闻,并分析
1.题目 爬取一下5家的加拿大新闻网站包含"China" / "Chinese"的数据,时间范围为2020年1月日至今,分析每家媒体文章的词云图.情感趋势图等. ...
- scrapy+selenium爬取B站生活区热门视频信息!
在爬取动态网页时,一般尽量先找相应网页的API接口.但当接口不好找(或者接口的URL中含有加密参数)时,这时候就需要selenium来帮忙了.但由于selenium爬取速度比较慢,此时结合scrapy ...
- python爬虫——scrapy+selenium爬取新浪微博及评论
本文主要对爬取过程中所用到的知识做简单总结,最后有项目链接. 一.项目简介 本项目利用python的scrapy框架+selenium模拟登陆微博来爬取带有关键字的微博及微博下面的评论(1 .2级评论 ...
- 使用 Scrapy + Selenium 爬取动态渲染的页面
点击上方蓝字关注我们! 背景 在通过scrapy框架进行某些网站数据爬取的时候,往往会碰到页面动态数据加载的情况发生,如果直接使用scrapy对其url发请求,是绝对获取不到那部分动态加载出来的数据值 ...
- scrapy+selenium爬取某招聘网站的职位、公司、面试评论
前一段时间因某些原因再次与爬虫碰面了,这次是爬取拉勾网的一些信息并利用wordcloud生成词云,并使用pyechart生成一些统计信息什么的 爬取前还是要观察拉勾网的一个页面结构,一般都是有规律可循 ...
- python3 使用selenium爬取QQ空间说说信息
使用PhantomJS,事先需要下载PhantomJS from selenium import webdriver import time#使用selenium driver = webdriver ...
- scrapy+selenium爬取UC头条网站
Scrapy是Python优秀的爬虫框架,selenium是非常好用的自动化WEB测试工具,两者结合可以非常容易对动态网页进行爬虫. 本文的需求是抓取UC头条各个板块的内容.UC头条(https:// ...
最新文章
- Mybatis实现物理分页
- 如何自动修复XP/VISTA/WIN7系统引导的工具(NTBootAutofix 2.02)
- 我理解的Future模式
- C++中的const和指针组合
- Everything本地文件检索 快速搜索/共享神器
- 转录组学分析之基因芯片的预处理
- 威密 android,勇士这赛季的结局,是否开始就已注定
- 第一篇 外贸企业出口退税
- linux相关操作命令(*)
- 2021年中国云游戏产业发展环境(PEST)分析:中国云游戏服务拥有光明前景[图]
- 用python自动办公_用Python自动办公,做职场高手
- CVPR 2021 | 目标引导的人类注意力估计提升零样本学习
- 计算机怎么不读u盘,老司机告诉你电脑不读U盘的解决方法
- 记一次网站迁移的过程
- Linux下面bzero函数学习笔记
- 【应用随机过程】03. 马尔可夫链的状态
- C#获取目录下所有文件的列表——最白话,手把手教你做系列。
- Redis(2) redis-cli 客户端操作Redis - 常用命令大全
- socket.io连接域名
- 智能门铃中可视对讲的回音消除