Julia's BLOG

用Scrapy和xpath爬取网页-1

2018-02-13

一、Scrapy

首先,Scrapy是一个爬虫框架,用来爬取网页。接下来的工作基于Scrapy的基本应用。

1)关于Scrapy的部署

首先我电脑里已经有python2 和python3。

python3会带有pip。

我是用pip来安装scrapy的。

首先检测一下pip3版本。

1
2
pip3 --version
pip 9.0.1 from /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (python 3.5)

然后用pip3安装Scrapy。【高亮】此处S大写。

1
pip3 install Scrapy

接下来测试一下Scrapy的版本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Scrapy 1.5.0 - no active project

Usage:
scrapy <command> [options] [args]

Available commands:
bench Run quick benchmark test
fetch Fetch a URL using the Scrapy downloader
genspider Generate new spider using pre-defined templates
runspider Run a self-contained spider (without creating a project)
settings Get settings values
shell Interactive scraping console
startproject Create new project
version Print Scrapy version
view Open URL in browser, as seen by Scrapy

[ more ] More commands available when run from project directory

Use "scrapy <command> -h" to see more info about a command

ok 此时Scrapy已经部署完毕

2)用Scrapy创建项目(此例中不必须)

在命令行中新建项目(此处spider为项目名)

1
scrapy startproject spider

二、爬取网页数据

1)我们随便测试一个网站

随便登录一个网站并且拷贝地址。在终端(即命令行)中运行。(如下地址可替换为任一网站)

1
scrapy shell http://bj.ganji.com/fang1/

2)在默认浏览器中打开刚刚爬取的网页

1
view(response)

爬取的网页会自动打开,此时我们会发现与原来的网页一模一样。

3)打开开发者模式下web控制台

4)用xpath插件获取要爬取的数据地址

此文打算爬取租房网站的房屋信息和价格。所以我们先获取价格的xpath。

如图-1

1

5)终端中运行以下命令测试结果

1
response.xpath("此处为获取的xpath地址").extract()

如图-2

2

6)观察想要获取的xpath的异同并爬取数据

比如此例中发现,不同价格的xpath均为

1
.//div[n]/dl/dd[5]/div[1]/span[1]

n为从1开始增大的整数。

我们还发现,每个div的id都不同,但是class是相同的。至此,我们找到了这些数据的共同点。采取用class来爬取数据。

如图-3

3

此例中为

1
.//div[@class='f-list-item ershoufang-list']/...

如图-4 以获取当前页面所有的租房价格。

4

以此类推,租房信息也是一样的思路。

如图-5

5

只需稍加处理便可进行数据分析。

以上。

Tags: python
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章