python爬虫框架scrapy入门,爬取数据存入数据库
- 共 610 次检阅

# -*- coding: utf-8 -*-

import scrapy
import time
from bs4 import BeautifulSoup
from scrapyMysql.items import ScrapymysqlItem  # 引入item


class InputmysqlSpider(scrapy.Spider):
    name = "inputMysql"
    # allowed_domains = ["啥也不是"]
    # 定义需要爬取的url
    start_urls = ['http://网址是啥?/']

    def parse(self, response):
        # 解析:作者的名字与句子
        div_list = response.css('.news-main')
        for div in div_list:
            # xpth返回的一定是列表 ,但是列表元素一定是 select类型,

            # 获取文章标题
            title = div_list.css('h1 span::text').getall()
            # 获取文章正文
            content = div_list.css('.news-cnt').getall()
            # 转换标题位字符串
            title = ''.join(title)
            # 转换正文为字符串
            content = ''.join(content)
            # 去除多余的标签吗
            title = BeautifulSoup(title, 'html.parser')
            # 取文本内容
            title = title.get_text()
            # 去掉空格
            title = title.strip()
            # 基于换行分割正文
            a11 = content.split('\n')
            #遍历分割后的正文段落
            for a22 in a11:
                # 实例化item类
                item = ScrapymysqlItem()
                # 输出时间
                now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                # 去掉分割后正文的多余字符
                a22 = a22.lstrip()
                # 去掉分割后的空格
                a22 = a22.strip('   ')
                # 处理分割后的标签
                a22 = BeautifulSoup(a22, 'html.parser')
                # 只获取分割后的文字
                a22 = a22.get_text()
                # 去掉分割后文字签名的空格
                a22 = a22.lstrip('\u3000')
                # 计算处理整个段落的长度
                a33 = (len(a22))
                # 如果段落长度小于100 跳过循环从头开始
                if a33 < 100:
                    continue
                # 赋值变量 标题
                item['title'] = title
                # 赋值变量 段落
                item['content'] = a22
                # 赋值变量 时间
                item['time1'] = now
                # 赋值变量 时间
                item['time2'] = now
                print('--------------------------------------------')
                # 把取到的数据提交给pipline处理
                yield item
                # 输出item内容
                print(item)

                print('--------------------------------------------')
                # print(item)


        #  寻找下一篇或者上一篇的链接
        next_page = response.css('.news-recommend li a::attr(href)')[0].getall()  # css选择器提取下一页链接
        # 转换该链接位字符串
        next_page = ''.join(next_page)
        # 输出上一篇或者下一篇的连接
        print(next_page)
        # 判断是否存在下一页
        if next_page is not None:
            # 赋值上一篇或者下一遍的变量
            next_page = response.urljoin(next_page)
            # 提交给parse继续抓取下一页
            yield scrapy.Request(next_page, callback=self.parse)

 

分享到:

这篇文章还没有评论

发表评论