分析网站结构
爬取blog.jobbole.com
该网站提供了所有文章的URL
新建虚拟环境(指定虚拟环境)
mkvirtualenv --python=路径 虚拟环境名字
安装scrapy(使用豆瓣源)
workon 虚拟环境名,进入虚拟环境后
pip install -i https://pypi.douban.com/simple/ scrapy
新建Scrapy工程
scrapy startproject 项目名
利用模板新建爬虫文件
在项目目录下
scrapy genspider jobbole blog.jobbole.com

继承了scrapy.Spider类,start_urls是一个list,可以放入想爬取的所有的URL。

对start_urls 进行遍历,yield Request交给Scrapy的下载器,下载完之后,进入到parse函数中,有一个response对象。
自定义main文件调用命令行使pycharm可以调试
os.path.abspath(__file__) # 得到当前文件的绝对路径
os.path.dirname(os.path.abspath(__file__)) # 得到当前文件的父目录
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
execute(["scrapy","crawl","jobbole"]) # 启动jobbole爬虫
注意settings.py 的ROBOTSTXT_OBEY协议设置为False
出现错误:No module named 'win32api'
因为windows下缺少这个包,通过pip命令安装
pip install -i 豆瓣源 pypiwin32
通过xpath提取值
xpath使用路径表达式在xml和html中进行导航
xpath语法
1. article:选取所有article元素的所有子节点
2. /article:选取根元素article
3. article/a: 属于article的子元素的a元素
4. //div: 获取所有div
5. article//div: article下的所有div
6. //@class: 选取所有名为class的属性
/article/div[1]
/article/div[last()]
//div[@lang='eng'] 取lang属性为eng的div
/div/* div下的所有子节点
//* 选取所有元素
//div[@*] 选取所有带属性的元素
response.xpath('//*[@id="post-110287"]/div[1]/h1/text') # xpath提取标题
response.xpath('//span[contains(@class,'vote-post-up')]') # 找一个span,他的class包含vote-post-up
通过CSS选择器提取值
response.css('.entry-header h1::text').extract()
关键代码
from scrapy.http import Request
from urllib import parse # python2 中是urlparse



Item

Scrapy 自动下载图片pipeline设置

no module PIL报错:
pip install pillow

将数据作为json文件保存


将数据插入数据库中
安装mysql驱动:pip install mysqlclient





网友评论