首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >软件工程实践专题第一次作业

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

作者头像
py3study
发布2020-01-21 11:41:20
2240
发布2020-01-21 11:41:20
举报
文章被收录于专栏:python3python3python3

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

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

运行结果
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-05-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档