页面元素解析 原

1.解析字段信息

  • 我们知道蜘蛛运行时会下载要爬取的页面,然后传给给start_urls,页面的返回对象response响应体就会封装到parse方法response对象里面,然后通过response对象css选择器定位元素,返回一个selector对象,通过extract()方法来提取selector对象中标签的信息。

  • 那现在我们使用dribbble网站来试着解析字段信息,创建一个dribbble蜘蛛,就和之前创建csdn一样,然后将测试页面中的execute()方法中的参数改为需要测试的蜘蛛页面中的name属性值。

import scrapy
from urllib import parse
from scrapy.http import Request class DribbbleSpider(scrapy.Spider): name = 'dribbble' allowed_domains = ['dribbble.com'] start_urls = ['https://dribbble.com/stories'] def parse(self, response): # 获取a标签的url值 # urls = response.css('h2 a::attr(href)').extract() a_nodes = response.css('header div.teaser a') for a_node in a_nodes: # print(a_node) a_url = a_node.css('::attr(href)').extract()[0] a_image_url = a_node.css('img::attr(src)').extract()[0] yield Request(url=parse.urljoin(response.url, a_url), callback=self.parse_analyse, meta={'a_image_url': a_image_url}) def parse_analyse(self, response): a_image_url = response.meta.get('a_image_url') title = response.css('.post header h1::text').extract()[0] date = response.css('span.date::text').extract_first() print('图片的url是:{}'.format(a_image_url)) print('标题是: {}'.format(title)) print('时间是:{}'.format(date.strip())) 

2.构建数据模型

  • 我们在创建模板时会自动生成一些文件,items.py文件就是其中一个,我们构建数据模型就需要用到这个文件,这个文件会自动生成一个modle,这个modle会继承scrapy.Item,然后我们可以根据我们的需求在自动生成的这个modle中随意创建字段;
import scrapy
class XkdDribbbleSpiderItem(scrapy.Item): title = scrapy.Field() a_image_url = scrapy.Field() date = scrapy.Field() 
  • 创建好字段之后,需要在spider中添加构建模型,最后让构建模型中的字段和之前modle中的字段名一致,防止赋值出错; 在spider中添加构建模型首先需要实例化items.py文件中的modle,然后通过实例化对象添加字段到modle中,最后将数据模型进行落地,让数据持久化。把实例化对象返回到pipelines.py中;
import scrapy
from urllib import parse
from scrapy.http import Request from ..items import XkdDribbbleSpiderItem from datetime import datetime class DribbbleSpider(scrapy.Spider): name = 'dribbble' allowed_domains = ['dribbble.com'] start_urls = ['https://dribbble.com/stories'www.bdqxylgw.com] def parse(self, response): # 获取a标签的url值 # urls = response.css('h2 a::attr(href)'www.zhongxinyuLegw3.com).extract() a_nodes = response.css('header div.teaser www.seoxinyang.cn a www.yaoshiyulegw.com') for a_node in a_nodes: # print(a_node) a_url = a_node.css('::attr(href)').extract()[0] a_image_url = a_node.css('img::attr(src)').extract()[0] yield Request(url=parse.urljoin(response.url, a_url), callback=self.parse_analyse, meta={'a_image_url': a_image_url}) def parse_analyse(self, response): a_image_url = response.meta.get('a_image_url') title = response.css(www.oushenggw.com'.post header h1::text').extract()[0] date = response.css(www.honghaiyLpt.com'span.date::text').extract_first() date = date.strip(www.yifayule2d.com) date = datetime.strptime(date, '%b %d, %Y').date() # 构建模型 dri_item = XkdDribbbleSpiderItem() dri_item['a_image_url'] = a_image_url dri_item['title'] = title dri_item['date'] = date yield dri_item

猜你喜欢

转载自www.cnblogs.com/qwangxiao/p/11088239.html