当前位置: 移动技术网 > IT编程>脚本编程>Python > 软件工程实践专题第一次作业

软件工程实践专题第一次作业

2019年03月06日  | 移动技术网IT编程  | 我要评论

泰剧爱的味道,哑巴小新娘:总裁的逃妻,错姻缘 匪我思存

对伯乐在线所有文章进行爬取

使用scrapy框架

jobbolen.py

# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import request
from urllib import parse
from scrapytext.items import article_item
class jobbolenspider(scrapy.spider):
name = 'jobbolen'
allowed_domains = ['blog.jobbole.com']
start_urls = ['http://blog.jobbole.com/all-posts/']

def parse(self, response):
re_nodes= response.css('#archive .floated-thumb .post-thumb a')
for re_node in re_nodes:
image_url=re_node.css("img::attr(src)").extract_first()
re_url=re_node.css('::attr(href)').extract_first()
yield request(url=parse.urljoin(response.url,re_url),meta={'front_url_image':image_url},callback=self.text_parse)#yield交给scrapy进行自动下载
next_urls=response.css('.next.page-numbers::attr(href)').extract_first()
if next_urls:
yield request(url=parse.urljoin(response.url, re_url), callback=self.parse)

def text_parse(self,response):
article_item=article_item()
re_title = response.css('.entry-header h1::text').extract()[0]
re_text = response.css('.entry p::text').extract()
front_image=response.meta.get("front_url_image","")
article_item["title"]=re_title
article_item["text"]=re_text
article_item["front_image"]=front_image
yield article_item

items.py配置
# -*- coding: utf-8 -*-

# define here the models for your scraped items
#
# see documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class scrapytextitem(scrapy.item):
# define the fields for your item here like:
# name = scrapy.field()
pass
class article_item(scrapy.item):
title=scrapy.field()
text=scrapy.field()
front_image=scrapy.field()
front_image_path=scrapy.field()
setting.py配置
import os
robotstxt_obey = false
images_urls_field ="front_image"#从item中找出那个是要保存的
project_dir=os.path.abspath(os.path.dirname(__file__))
images_store=os.path.join(project_dir,'images')#将图片保存在本地文件中



main.py
# -*- coding: utf-8 -*-
__auther__="booby"
from scrapy.cmdline import execute
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
execute(["scrapy","crawl","jobbolen"])


运行出现错误:

解决方案:

由于将一个字符串传递给数组导致错误

将jobbolen.py中的front_image改成[front_image]

运行结果

 

 


提取出文章及标题和封面图片




















如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网