• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python Scrapy爬虫框架的使用

python 搞代码 4年前 (2022-01-09) 26次浏览 已收录 0个评论

导读:如何使用scrapy框架实现爬虫的4步曲?什么是CrawSpider模板?如何设置下载中间件?如何实现Scrapyd远程部署和监控?想要了解更多,下面让我们来看一下如何具体实现吧!

Scrapy安装(mac)

pip install scrapy

注意:不要使用commandlinetools自带的python进行安装,不然可能报架构错误;用brew下载的python进行安装。

Scrapy实现爬虫

新建爬虫

scrapy startproject demoSpider,demoSpider为项目名。

确定目标

编写items.py,如添加目标字段:person = scrapy.Field()

制作爬虫

scrapy genspider demo “baidu.com”,创建demo爬虫文件,指定爬取域。

修改demo.py里的start_urls的地址为自己想爬取的地址如:https://www.cnblogs.com/teark/

随意修改parse()方法,如保本文来源gaodai#ma#com搞@@代~&码网存所爬取的页面,可以这样:

def parse(self, response):
  with open("teark.html", "w") as f:
    f.write(response.text)

运行爬虫,看看效果:scrapy crawl demo

有了保存的页面后(可注释掉或删掉保存页面的代码),根据页面结构提取所需数据,一般用xpath表达式,如:

def parse(self, response):
  for _ in response.xpath("//div[@class='teark_article']"):
    item = ItcastItem()
    title = each.xpath("h3/text()").extract()
    content = each.xpath("p/text()").extract()
    item['title'] = title[0]
    item['content'] = content[0]
    yield item

保存数据:scrapy crawl demo -o demo.json(以下格式都行:jsonl,jsonl,csv,xml)

注:该过程在取值中经常需要页面调试,使用scrapy shell(最好先安装ipython,有语法提示),调试好了再放到代码里,如:

scrapy shell "https://www.cnblogs.com/teark/"
response.xpath('//*[@class="even"]')
print site[0].xpath('./td[2]/text()').extract()[0]

处理内容

pipline常用来存储内容,pipline.py中必须实现process_item()方法,该方法必须返回Item对象,如:

import json

class ItcastJsonPipeline(object):

  def __init__(self):
    self.file = open('demo.json', 'wb')

  def process_item(self, item, spider):
    content = json.dumps(dict(item), ensure_ascii=False) + "\n"
    self.file.write(content)
    return item

  def close_spider(self, spider):
    self.file.close()

在settings.py中添加ITEM_PIPELINES配置,如:

ITEM_PIPELINES = {
  "demoSpider.pipelines.DemoJsonPipeline":300
}

重新启动爬虫:scrapy crawl demo,看看当前目录是否生成demo.json

CrawlSpiders

CrawlSpider是spider的派生类,为了从爬取的网页中获取link并继续爬取。

快速创建 CrawlSpider模板:scrapy genspider -t crawl baidu baidu.com

Rule类制定了爬取规则;LinkExtractors类为了提取链接,如:

scrapy shell "http://teark.com/article.php?&start=0#a"

from scrapy.linkextractors import LinkExtractor

# 注意转义字符&
page_lx = LinkExtractor(allow=('comment.php?\&start=\d+'))
page_lx.extract_links(response)

测试完后就知道了allow和rules了,修改spider代码:

#提取匹配 'http://teark.com/article.php?&start=\d+'的链接
page_lx = LinkExtractor(allow = ('start=\d+'))

rules = [
  #提取匹配,并使用spider的parse方法进行分析;并跟进链接(没有callback意味着follow默认为True)
  Rule(page_lx, callback = 'parseContent', follow = True)
]

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python Scrapy爬虫框架的使用

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址