广告
返回顶部
首页 > 资讯 > 后端开发 > Python >软件工程实践专题第一次作业
  • 385
分享到

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

作业软件工程专题 2023-01-30 23:01:56 385人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

对伯乐在线所有文章进行爬取 使用scrapy框架 jobbolen.py # -*- coding: utf-8 -*-import scrapyfrom scrapy.Http import Requestfrom urllib imp

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

使用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]

运行结果

 

 

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




















--结束END--

本文标题: 软件工程实践专题第一次作业

本文链接: https://www.lsjlt.com/news/181289.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作