本系列文章主要记录和讲解pyspider的示例代码,希望能抛砖引玉。pyspider示例代码官方网站是http://demo.pyspider.org/。上面的示例代码太多,无从下手。因此本人找出一些比较经典的示例进行简单讲解,希望对新手有一些帮助。

示例说明:

本示例主要是PyQuery解析返回的response页面数据。response.doc解析页面数据是pyspider的主要用法,应该熟练掌握基本使用方法。其他返回类型示例见后续文章。

pyspider爬取的内容通过回调的参数response返回,response有多种解析方式。
1、response.json用于解析json数据
2、response.doc返回的是PyQuery对象
3、response.etree返回的是lxml对象
4、response.text返回的是unicode文本
5、response.content返回的是字节码

使用方法:

PyQuery可以采用CSS选择器作为参数对网页进行解析。 关于PyQuery更多用法,可以参考PyQuery complete API。

PyQuery官方参考手册: https://pythonhosted.org/pyquery/

response.doc('.ml.mlt.mtw.cl > li').items()
response.doc('.pti > .pdbt > .authi > em > span').attr('title')

CSS选择器:更多详情请参考CSS Selector Reference

选择器 示例 示例说明
.class .intro Selects all elements with class=”intro”
#id #firstname Selects the element with id=”firstname”
element p Selects all <p> elements
element,element div, p Selects all <div> elements and all <p> elements
element element div p Selects all <p> elements inside <div> elements
element>element div > p Selects all <p> elements where the parent is a <div> element
[attribute] [target] Selects all elements with a target attribute
[attribute=value] [target=_blank] Selects all elements with target=”_blank”
[attribute^=value] a[href^=”https”] Selects every <a> element whose href attribute value begins with “https”
[attribute$=value] a[href$=”.pdf”] Selects every <a> element whose href attribute value ends with “.pdf”
[attribute*=value] a[href*=”w3schools”] Selects every <a> element whose href attribute value contains the substring “w3schools”
:checked input:checked Selects every checked <input> element

示例代码:

1、PyQuery基本语法应用

#!/usr/bin/env python
# -*- encoding: utf- -*-
# Created on -- ::
# Project: douban_rent from pyspider.libs.base_handler import * groups = {'上海租房': 'https://www.douban.com/group/shanghaizufang/discussion?start=',
'上海租房@长宁租房/徐汇/静安租房': 'https://www.douban.com/group/zufan/discussion?start=',
'上海短租日租小组 ': 'https://www.douban.com/group/chuzu/discussion?start=',
'上海短租': 'https://www.douban.com/group/275832/discussion?start=',
} class Handler(BaseHandler):
crawl_config = {
} @every(minutes= * )
def on_start(self):
for i in groups:
url = groups[i] + ''
self.crawl(url, callback=self.index_page, validate_cert=False) @config(age= * * * )
def index_page(self, response):
for each in response.doc('.olt .title a').items():
self.crawl(each.attr.href, callback=self.detail_page) #next page
for each in response.doc('.next a').items():
self.crawl(each.attr.href, callback=self.index_page) @config(priority=)
def detail_page(self, response):
count_not=
notlist=[]
for i in response.doc('.bg-img-green a').items():
if i.text() <> response.doc('.from a').text():
count_not +=
notlist.append(i.text())
for i in notlist: print i return {
"url": response.url,
"title": response.doc('title').text(),
"author": response.doc('.from a').text(),
"time": response.doc('.color-green').text(),
"content": response.doc('#link-report p').text(),
"回应数": len([x.text() for x in response.doc('h4').items()]) ,
# "最后回帖时间": [x for x in response.doc('.pubtime').items()][-].text(),
"非lz回帖数": count_not,
"非lz回帖人数": len(set(notlist)),
# "主演": [x.text() for x in response.doc('.actor a').items()],
}

2、PyQuery基本语法应用

#!/usr/bin/env python
# -*- encoding: utf- -*-
# Created on -- ::
# Project: learn_pyspider_db from pyspider.libs.base_handler import *
import re class Handler(BaseHandler):
crawl_config = {
} @every(minutes= * )
def on_start(self):
self.crawl('http://movie.douban.com/tag/', callback=self.index_page) @config(age= * * * )
def index_page(self, response):
for each in response.doc('.tagCol a').items():
self.crawl(each.attr.href, callback=self.list_tag_page) @config(age= * * * )
def list_tag_page(self, response):
all = response.doc('.more-links')
self.crawl(all.attr.href, callback=self.list_page) @config(age=***)
def list_page(self, response):
for each in response.doc('.title').items():
self.crawl(each.attr.href, callback=self.detail_page)
# craw the next page
next_page = response.doc('.next > a')
self.crawl(next_page.attr.href, callback=self.list_page) @config(priority=)
def detail_page(self, response):
director = ''
for item in response.doc('#info > span > .pl'):
if item.text == u'导演':
next_item = item.getnext()
director = next_item.getchildren()[].text
break
return {
"url": response.url,
"title": response.doc('title').text(),
"director": director,
}

3、PyQuery复杂选择及翻页处理

#!/usr/bin/env python
# -*- encoding: utf- -*-
# Created on -- ::
# Project: qx_zj_poi2 import re
from pyspider.libs.base_handler import * class Handler(BaseHandler):
crawl_config = {
} @every(minutes= * )
def on_start(self):
self.crawl('http://www.poi86.com/poi/amap/province/330000.html', callback=self.city_page) @config(age= * * )
def city_page(self, response):
for each in response.doc('body > div:nth-child(2) > div > div.panel-body > ul > li > a').items():
self.crawl(each.attr.href, callback=self.district_page) @config(age= * * )
def district_page(self, response):
for each in response.doc('body > div:nth-child(2) > div > div.panel-body > ul > li > a').items():
self.crawl(each.attr.href, callback=self.poi_idx_page) @config(age= * * )
def poi_idx_page(self, response):
for each in response.doc('td > a').items():
self.crawl(each.attr.href, callback=self.poi_dtl_page)
# 翻页
for each in response.doc('body > div:nth-child(2) > div > div.panel-body > div > ul > li:nth-child(13) > a').items():
self.crawl(each.attr.href, callback=self.poi_idx_page) @config(priority=)
def poi_dtl_page(self, response):
return {
"url": response.url,
"id": re.findall('\d+',response.url)[],
"name": response.doc('body > div:nth-child(2) > div:nth-child(2) > div.panel-heading > h1').text(),
"province": response.doc('body > div:nth-child(2) > div:nth-child(2) > div.panel-body > ul > li:nth-child(1) > a').text(),
"city": response.doc('body > div:nth-child(2) > div:nth-child(2) > div.panel-body > ul > li:nth-child(2) > a').text(),
"district": response.doc('body > div:nth-child(2) > div:nth-child(2) > div.panel-body > ul > li:nth-child(3) > a').text(),
"addr": response.doc('body > div:nth-child(2) > div:nth-child(2) > div.panel-body > ul > li:nth-child(4)').text(),
"tel": response.doc('body > div:nth-child(2) > div:nth-child(2) > div.panel-body > ul > li:nth-child(5)').text(),
"type": response.doc('body > div:nth-child(2) > div:nth-child(2) > div.panel-body > ul > li:nth-child(6)').text(),
"dd_map": response.doc('body > div:nth-child(2) > div:nth-child(2) > div.panel-body > ul > li:nth-child(7)').text(),
"hx_map": response.doc('body > div:nth-child(2) > div:nth-child(2) > div.panel-body > ul > li:nth-child(8)').text(),
"bd_map": response.doc('body > div:nth-child(2) > div:nth-child(2) > div.panel-body > ul > li:nth-child(9)').text(),
}

pyspider示例代码三:用PyQuery解析页面数据的更多相关文章

  1. pyspider用PyQuery解析页面数据

    示例说明: 本示例主要是PyQuery解析返回的response页面数据.response.doc解析页面数据是pyspider的主要用法,应该熟练掌握基本使用方法.其他返回类型示例见后续文章. py ...

  2. pyspider示例代码:解析JSON数据

    pyspider示例代码官方网站是http://demo.pyspider.org/.上面的示例代码太多,无从下手.因此本人找出一下比较经典的示例进行简单讲解,希望对新手有一些帮助. 示例说明: py ...

  3. pyspider示例代码二:解析JSON数据

    本系列文章主要记录和讲解pyspider的示例代码,希望能抛砖引玉.pyspider示例代码官方网站是http://demo.pyspider.org/.上面的示例代码太多,无从下手.因此本人找出一下 ...

  4. pyspider示例代码一:利用phantomjs解决js问题

    本系列文章主要记录和讲解pyspider的示例代码,希望能抛砖引玉.pyspider示例代码官方网站是http://demo.pyspider.org/.上面的示例代码太多,无从下手.因此本人找出一下 ...

  5. 找到你的位置(JS在页面中的位置)最常用的方式是在页面中head部分放置<script>元素,浏览器解析head部分就会执行这个代码,然后才解析页面的其余部分

    找到你的位置(JS在页面中的位置) 我们可以将JavaScript代码放在html文件中任何位置,但是我们一般放在网页的head或者body部分. 放在<head>部分 最常用的方式是在页 ...

  6. pyspider示例代码五:实现自动翻页功能

    实现自动翻页功能 示例代码一 #!/usr/bin/env python # -*- encoding: utf- -*- # Created on -- :: # Project: v2ex fro ...

  7. python爬虫解析页面数据的三种方式

    re模块 re.S表示匹配单行 re.M表示匹配多行 使用re模块提取图片url,下载所有糗事百科中的图片 普通版 import requests import re import os if not ...

  8. pyspider示例代码六:传递参数

    传递参数 示例一 #!/usr/bin/env python # -*- encoding: utf- -*- # vim: ts= sts= ff=unix fenc=utf8: # Created ...

  9. pyspider示例代码七:自动登陆并获得PDF文件下载地址

    自动登陆并获得PDF文件下载地址 #!/usr/bin/env python # -*- encoding: utf- -*- # Created on -- :: # Project: pdf_sp ...

随机推荐

  1. MyBatis_Study_002(进阶,增删改查)

    源码:https://github.com/carryLess/mbtsstd-002.git 1.主配置文件 <?xml version="1.0" encoding=&q ...

  2. test20181016 B君的第三题

    题意 B 君的第三题(haskell) 题目描述 大学四年,我为什么,为什么不好好读书,没找到和你一样的工作. B 君某天看到了这样一个题,勾起了无穷的回忆. 输入\(n, k\) 和一棵\(n\) ...

  3. 【转】Windows消息投递流程:WM_COMMAND消息流程

    原文网址:http://blog.csdn.net/hyhnoproblem/article/details/6182585 该示例通过研究基本的单文档程序的“文件”--“打开”命令,分析WM_COM ...

  4. linux之 CentOS/RHEL/Scientific Linux 6 & 7上安装Telnet

    声明: 在安装和使用Telnet之前,需要记住以下几点. 在公网(WAN)中使用Telnet是非常不好的想法.它会以明文的格式传输登入数据.每个人都可以看到明文.如果你还是需要Telnet,强烈建议你 ...

  5. Firefox渗透插件—Web渗透必备工具

    1:Firebug Firefox的 五星级强力推荐插件之一,不许要多解释 2:User Agent Switcher 改变客户端的User Agent的一款插件 3:Hackbar 攻城师们的必备工 ...

  6. js setInterval每隔一段时间执行一次

    js setInterval每隔一段时间执行一次setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式.setInterval() 方法会不停地调用函数,直到 clearI ...

  7. POJ1236学校网络——tarjan

    题目:http://poj.org/problem?id=1236 Tarjan+缩点.温习一下Tarjan的写法. 1.在缩点后的TAG中,有几个联通块等价于有几个入度为0的点! 2.把它们都联通相 ...

  8. PhoneGap 获得APP的VersionName

    1.首先安装cordova-plugin-app-version cordova plugin add cordova-plugin-app-version 2. 调用方法如下 function ge ...

  9. 列表查询SQL语句改造

    一个经常遇到到的场景,就是查询列表数据,列表数据由多张表构成 最简单的查询方法是先写一个查询单条数据的方法,比如这个方法中要查询十张表: 然后一个循环调用查单条的方法,这种逻辑上理解是比较简单的(因为 ...

  10. php日志函数error_log

    php内置打印log日志的函数,这个对php程序调试非常高效 1.配置 编辑php.ini文件 log_errors = On 设置log日志存储路径 error_log = /wwwroot/php ...