源码解析
class CrawlSpider(Spider):
rules = ()
def __init__(self, *a, **kw):
super(CrawlSpider, self).__init__(*a, **kw)
self._compile_rules()
# 首先调用parse()来处理start_urls中返回的response对象
# parse()则将这些response对象传递给了_parse_response()函数处理,并设置回调函数为parse_start_url()
# 设置了跟进标志位True
# parse将返回item和跟进了的Request对象
def parse(self, response):
return self._parse_response(response, self.parse_start_url, cb_kwargs={}, follow=True)
# 处理start_url中返回的response,需要重写
def parse_start_url(self, response):
return []
def process_results(self, response, results):
return results
# 从response中抽取符合任一用户定义'规则'的链接,并构造成Resquest对象返回
def _requests_to_follow(self, response):
if not isinstance(response, HtmlResponse):
return
seen = set()
# 抽取之内的所有链接,只要通过任意一个'规则',即表示合法
for n, rule in enumerate(self._rules):
links = [l for l in rule.link_extractor.extract_links(response) if l not in seen]
# 使用用户指定的process_links处理每个连接
if links and rule.process_links:
links = rule.process_links(links)
# 将链接加入seen集合,为每个链接生成Request对象,并设置回调函数为_repsonse_downloaded()
for link in links:
seen.add(link)
# 构造Request对象,并将Rule规则中定义的回调函数作为这个Request对象的回调函数
r = Request(url=link.url, callback=self._response_downloaded)
r.meta.update(rule=n, link_text=link.text)
# 对每个Request调用process_request()函数。该函数默认为indentify,即不做任何处理,直接返回该Request.
yield rule.process_request(r)
# 处理通过rule提取出的连接,并返回item以及request
def _response_downloaded(self, response):
rule = self._rules[response.meta['rule']]
return self._parse_response(response, rule.callback, rule.cb_kwargs, rule.follow)
# 解析response对象,会用callback解析处理他,并返回request或Item对象
def _parse_response(self, response, callback, cb_kwargs, follow=True):
# 首先判断是否设置了回调函数。(该回调函数可能是rule中的解析函数,也可能是 parse_start_url函数)
# 如果设置了回调函数(parse_start_url()),那么首先用parse_start_url()处理response对象,
# 然后再交给process_results处理。返回cb_res的一个列表
if callback:
#如果是parse调用的,则会解析成Request对象
#如果是rule callback,则会解析成Item
cb_res = callback(response, **cb_kwargs) or ()
cb_res = self.process_results(response, cb_res)
for requests_or_item in iterate_spider_output(cb_res):
yield requests_or_item
# 如果需要跟进,那么使用定义的Rule规则提取并返回这些Request对象
if follow and self._follow_links:
#返回每个Request对象
for request_or_item in self._requests_to_follow(response):
yield request_or_item
def _compile_rules(self):
def get_method(method):
if callable(method):
return method
elif isinstance(method, basestring):
return getattr(self, method, None)
self._rules = [copy.copy(r) for r in self.rules]
for rule in self._rules:
rule.callback = get_method(rule.callback)
rule.process_links = get_method(rule.process_links)
rule.process_request = get_method(rule.process_request)
def set_crawler(self, crawler):
super(CrawlSpider, self).set_crawler(crawler)
self._follow_links = crawler.settings.getbool('CRAWLSPIDER_FOLLOW_LINKS', True)
class scrapy.linkextractors.LinkExtractor(
allow = (),
deny = (),
allow_domains = (),
deny_domains = (),
deny_extensions = None,
restrict_xpaths = (),
tags = ('a','area'),
attrs = ('href'),
canonicalize = True,
unique = True,
process_value = None
)
class scrapy.spiders.Rule(
link_extractor,
callback = None,
cb_kwargs = None,
follow = None,
process_links = None,
process_request = None
)
LOG_FILE = "TencentSpider.log" LOG_LEVEL = "INFO"
模型类 import scrapy class CrawlyouyuanItem(scrapy.Item): # 用户名 username = scrapy.Field() # 年龄 age = scrapy.Field() # 头像图片的链接 header_url = scrapy.Field() # 相册图片的链接 images_url = scrapy.Field() # 内心独白 content = scrapy.Field() # 籍贯 place_from = scrapy.Field() # 学历 education = scrapy.Field() # 兴趣爱好 hobby = scrapy.Field() # 个人主页 source_url = scrapy.Field() # 数据来源网站 sourec = scrapy.Field() # utc 时间 time = scrapy.Field() # 爬虫名 spidername = scrapy.Field()
爬虫文件
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from CrawlYouYuan.items import CrawlyouyuanItem
import re
class YouyuanSpider(CrawlSpider):
name = 'youyuan'
allowed_domains = ['youyuan.com']
start_urls = ['http://www.youyuan.com/find/beijing/mm18-25/advance-0-0-0-0-0-0-0/p1/']
# 自动生成的文件不需要改东西,只需要添加rules文件里面Rule角色就可以
# 每一页匹配规则
page_links = LinkExtractor(allow=(r"youyuan.com/find/beijing/mm18-25/advance-0-0-0-0-0-0-0/p\d+/"))
# 每个人个人主页匹配规则
profile_links = LinkExtractor(allow=(r"youyuan.com/\d+-profile/"))
rules = (
# 没有回调函数,说明follow是True
Rule(page_links),
# 有回调函数,说明follow是False
Rule(profile_links, callback='parse_item', follow=True),
)
def parse_item(self, response):
item = CrawlyouyuanItem()
item['username'] = self.get_username(response)
# 年龄
item['age'] = self.get_age(response)
# 头像图片的链接
item['header_url'] = self.get_header_url(response)
# 相册图片的链接
item['images_url'] = self.get_images_url(response)
# 内心独白
item['content'] = self.get_content(response)
# 籍贯
item['place_from'] = self.get_place_from(response)
# 学历
item['education'] = self.get_education(response)
# 兴趣爱好
item['hobby'] = self.get_hobby(response)
# 个人主页
item['source_url'] = response.url
# 数据来源网站
item['sourec'] = "youyuan"
yield item
def get_username(self, response):
username = response.xpath("//dl[@class='personal_cen']//div[@class='main']/strong/text()").extract()
if len(username):
username = username[0]
else:
username = "NULL"
return username.strip()
def get_age(self, response):
age = response.xpath("//dl[@class='personal_cen']//dd/p/text()").extract()
if len(age):
age = re.findall(u"\d+岁", age[0])[0]
else:
age = "NULL"
return age.strip()
def get_header_url(self, response):
header_url = response.xpath("//dl[@class='personal_cen']/dt/img/@src").extract()
if len(header_url):
header_url = header_url[0]
else:
header_url = "NULL"
return header_url.strip()
def get_images_url(self, response):
images_url = response.xpath("//div[@class='ph_show']/ul/li/a/img/@src").extract()
if len(images_url):
images_url = ", ".join(images_url)
else:
images_url = "NULL"
return images_url
def get_content(self, response):
content = response.xpath("//div[@class='pre_data']/ul/li/p/text()").extract()
if len(content):
content = content[0]
else:
content = "NULL"
return content.strip()
def get_place_from(self, response):
place_from = response.xpath("//div[@class='pre_data']/ul/li[2]//ol[1]/li[1]/span/text()").extract()
if len(place_from):
place_from = place_from[0]
else:
place_from = "NULL"
return place_from.strip()
def get_education(self, response):
education = response.xpath("//div[@class='pre_data']/ul/li[3]//ol[2]/li[2]/span/text()").extract()
if len(education):
education = education[0]
else:
education = "NULL"
return education.strip()
def get_hobby(self, response):
hobby = response.xpath("//dl[@class='personal_cen']//ol/li/text()").extract()
if len(hobby):
hobby = ",".join(hobby).replace(" ", "")
else:
hobby = "NULL"
return hobby.strip()
管道文件
import json
import codecs
class CrawlyouyuanPipeline(object):
def __init__(self):
self.filename = codecs.open('content.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
html = json.dumps(dict(item), ensure_ascii=False)
self.filename.write(html + '\n')
return item
def spider_closed(self, spider):
self.filename.close()
BOT_NAME = 'CrawlYouYuan'
SPIDER_MODULES = ['CrawlYouYuan.spiders']
NEWSPIDER_MODULE = 'CrawlYouYuan.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:56.0)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
ITEM_PIPELINES = {
'CrawlYouYuan.pipelines.CrawlyouyuanPipeline': 300,
}
from scrapy import cmdline
cmdline.execute('scrapy crawl youyuan'.split())
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有