您现在的位置是:首页 > 文章详情

18、 Python快速开发分布式搜索引擎Scrapy精讲—Scrapy启动文件的配置—xpath表达式

日期:2019-07-03点击:447

http://www.bdyss.cn

http://www.swpan.cn

我们自定义一个main.py来作为启动文件

main.py

#!/usr/bin/env python # -*- coding:utf8 -*- from scrapy.cmdline import execute  #导入执行scrapy命令方法 import sys import os sys.path.append(os.path.join(os.getcwd())) #给Python解释器,添加模块新路径 ,将main.py文件所在目录添加到Python解释器 execute(['scrapy', 'crawl', 'pach', '--nolog'])  #执行scrapy命令

爬虫文件

# -*- coding: utf-8 -*- import scrapy from scrapy.http import Request import urllib.response from lxml import etree import re class PachSpider(scrapy.Spider):     name = 'pach'     allowed_domains = ['blog.jobbole.com']     start_urls = ['http://blog.jobbole.com/all-posts/']     def parse(self, response):         pass

xpath表达式

1、

image

2、

image

3、

image

基本使用

allowed_domains设置爬虫起始域名
start_urls设置爬虫起始url地址
parse(response)默认爬虫回调函数,response返回的是爬虫获取到的html信息对象,里面封装了一些关于htnl信息的方法和属性

responsehtml信息对象下的方法和属性
response.url获取抓取的rul
response.body获取网页内容
response.body_as_unicode()获取网站内容unicode编码
xpath()方法,用xpath表达式过滤节点
extract()方法,获取过滤后的数据,返回列表

# -*- coding: utf-8 -*- import scrapy class PachSpider(scrapy.Spider):     name = 'pach'     allowed_domains = ['blog.jobbole.com']     start_urls = ['http://blog.jobbole.com/all-posts/']     def parse(self, response):         leir = response.xpath('//a[@class="archive-title"]/text()').extract()  #获取指定标题         leir2 = response.xpath('//a[@class="archive-title"]/@href ').extract() #获取指定url         print(response.url)    #获取抓取的rul         print(response.body)   #获取网页内容         print(response.body_as_unicode())  #获取网站内容unicode编码         for i in leir:             print(i)         for i in leir2:             print(i)

 image
【转载自:http://www.lqkweb.com

原文链接:https://yq.aliyun.com/articles/707387
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章