1.1 页面解析
self
的含义:
在Python类中规定,函数的第一个参数是实例对象本身,并且约定俗成,把其名字写为self,参考:
https://blog.csdn.net/love666666shen/article/details/78189984
2 xpath常用命令
- 常用命令
'/html' :html节点
'/html/body/div/a' : 选中div子节点中的所有a
'//a' :选中文档中的所有a
'/html/body//img' :选中body后代中的所有img
'//a/text()' :选中a的所有文本
'//div/*/img' :选中div孙节点中的所有img
'//img/@scr' :选中所有Img的属性
'//@href' :选中所有的href属性
'//div[@id]' :选中所有含有id属性的div
'//div[@id="images"]' :选中所有含有id属性且值为“images”的div
- 案例
from scrapy.selector import Selector
from scrapy.http import HtmlResponse
import requests
body = requests.get('http://bang.dangdang.com/books/bestsellers/01.00.00.00.00.00-month-2018-6-1-1').text
response = HtmlResponse(url='http://example.com', body=body, encoding='utf-8')
name = response.xpath('//div[@class="name"]//@title').extract_first()
print(name)
name2 = response.css('div.name a::attr(title)').extract_first()
print(name2)
3 css常用命令
>>> response.css('img')
>>> response.css('div img')
>>> response.css('body>div')
>>> response.css('[style]')
>>> response.css('[id=images-1]')
>>> response.css('a.img')
>>> response.css('.img')
>>> response.css('a::text').extract()
>>> response.css('a::attr(href)').extract()
4 js 页面解析
- Splash 简介
Splash 是 Scrapy 官方推荐的 JavaScript 渲染引擎,是一款轻量级的无界面浏览器,类似于 PhantomJS - 安装
pip install scrapy-splash
4.1 SplashRequest 构造器参数
- scrapy_splash中定义了一个SplashRequest类,用户只需使用scrapy_splash.SplashRequest(替代scrapy.Request)提交请求即可。
import scrapy_splash
scrapy_splash.SplashRequest()
from scrapy_splash import SplashRequest
SplashRequest()
- 下面是 SplashRequest 构造器方法中的一些常用参数。
- ① url :与scrapy.Request中的url相同,也就是待爬取页面的url(注意,不是Splash服务器地址)。
- ② headers: 与scrapy.Request中的headers相同。
- ③ cookies:与scrapy.Request中的cookies相同。
- ④ args:传递给Splash的参数(除url以外),如wait、timeout、images、js_source等。
4.2 流程
$ scrapy startproject splash_examples
- 第二步:在setting.py 中对scrapy-splash 进行配置,添加内容如下:
SPLASH_URL = 'http://localhost:8050'
DOWNLOADER_MIDDLEWARES = {
'scrapy_splash.SplashCookiesMiddleware': 723,
'scrapy_splash.SplashMiddleware': 725,
'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
SPIDER_MIDDLEWARES = {
'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
}
5 单词
- extract() 提取
- yield 生成器