pip install scrapy
windows可能安装失败,需要先安装c++库或twisted,
pip install twisted
scrapy startproject tutorial
该命令将会创建包含下列内容的 tutorial 目录:
tutorial/
scrapy.cfg
tutorial/
__init__.py
items.py
pipelines.py
settings.py
spiders/
__init__.py
...
scrapy.cfg: 项目的配置文件
tutorial/: 该项目的python模块。之后您将在此加入代码。
tutorial/items.py: 项目中的item文件.
tutorial/pipelines.py: 项目中的pipelines文件.
tutorial/settings.py: 项目的设置文件.
tutorial/spiders/: 放置spider代码的目录.
为了创建一个Spider,您必须继承 scrapy.Spider 类,定义以下三个属性
scrapy genspider dmoz dmoz.com 终端命令可以直接完成这步操作
1 import scrapy
2
3 class DmozSpider(scrapy.Spider):
4 name = "dmoz"
5 allowed_domains = ["dmoz.org"]
6 start_urls = [
7 "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
8 "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
9 ]
10
11 def parse(self, response):
12 filename = response.url.split("/")[-2]
13 with open(filename, 'wb') as f:
14 f.write(response.body)
scrapy crawl dmoz
过程:Scrapy为Spider的 start_urls 属性中的每个URL创建了 scrapy.Request 对象,并将 parse 方法作为回调函数(callback)赋值给了Request;Request对象经过调度,执行生成 scrapy.http.Response 对象并送回给spider parse() 方法。
xpath(): 传入xpath表达式,返回该表达式所对应的所有节点的selector list列表 。
css(): 传入CSS表达式,返回该表达式所对应的所有节点的selector list列表.
extract(): 序列化该节点为unicode字符串并返回list。
re(): 根据传入的正则表达式对数据进行提取,返回unicode字符串list列表。
scrapy shell "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/"
1 import scrapy
2
3 class DmozSpider(scrapy.Spider):
4 name = "dmoz"
5 allowed_domains = ["dmoz.org"]
6 start_urls = [
7 "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
8 "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
9 ]
10
11 def parse(self, response):
12 for sel in response.xpath('//ul/li'):
13 title = sel.xpath('a/text()').extract()
14 link = sel.xpath('a/@href').extract()
15 desc = sel.xpath('text()').extract()
16 print title, link, desc
请使用手机"扫一扫"x
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有