Scrapy爬取和讯博客个人博客的信息并写人数据库

一、爬虫实现功能

              1)爬取博客中一个用户的所有博文信息

              2)将博文的文章名、文章URL、文章点击数、文章评论数等信息提取出来

              3)将提取出来的文章名、文章URL、文章点击数、文章评论数等信息写入MySql数据库中存储


二、爬虫实现

1) 创建存储数据的数据库及其表

       1.通过mysql创建数据库及其表。

          借助pymysql模块中的connect函数连接数据库和query函数执行SQL语句进行建数据库和表

       2.在mysql窗口创建


        表结构:

CREATE TABLE myhexun(

               id INT(10) AUTO_INCREMENT PRIMARY KEY NOT NULL,

               name VARCHAR(30),

               url VARCHAR(100),

               hits INT(15),

               comment INT(15));

2)创建爬虫项目

   在CMD命令行中执行:

           scarpy startproject hexunpjt

3)修改items文件

# -*- 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 HexunpjtItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    name = scrapy.Field()
    url = scrapy.Field()
    hits = scrapy.Field()
    comment = scrapy.Field()

4)修改pipelines文件

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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql

class HexunpjtPipeline(object):
    def __init__(self):
        self.conn = pymysql.connect(host = "127.0.0.1",user = "root",passwd = "root",db = "hexun")
    def process_item(self, item, spider):
        #每一个博文列表页中包含多篇博文的信息,我们可以通过for循环一次处理各博文的信息
        for i in range(0,len(item["name"])):
            name = item["name"][i]
            url = item["url"][i]
            hits = item["hits"][i]
            comment = item["comment"][i]
            sql = "INSERT INTO myhexun(name,url,hits,comment) VALUES('"+ name + "','" + url +"', '" + hits + "','" + comment + "')"
            self.conn.query(sql) #插入
            self.conn.commit()   #提交
        return item
    def close_spider(self):
        self.conn.close()
5)修改settings文件

     开启ITEM_PIPELINES

ITEM_PIPELINES = {
    'hexunpjt.pipelines.HexunpjtPipeline': 300,
}

6)创建基于basic爬虫

    在CMD命令行中执行:scrapy genspider -t basic myhexunspd hexun.com

7)分析网页中要爬取的数据,写出对应的正则表达式或XPATH表达式

8)修改myhexunspd文件

# -*- coding: utf-8 -*-
import scrapy
import re
import urllib.request
from hexunpjt.items import HexunpjtItem
from scrapy.http import Request


class MyhexunspdSpider(scrapy.Spider):
    name = 'myhexunspd'
    allowed_domains = ['hexun.com']
    #设置要爬取的用户的uid,为后续构造爬取网址做准备
    uid = "fjrs168"
    start_urls = ['http://hexun.com/']
    def start_requests(self):
        yield Request("http://" + str(self.uid) + ".blog.hexun.com/p1/default.html",
                headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.3964.2 Safari/537.36"})

    def parse(self, response):
        item = HexunpjtItem()
        item["name"] = response.xpath("//span[@class='ArticleTitleText']/a/text()").extract()
        item["url"] = response.xpath("//span[@class='ArticleTitleText']/a/@href").extract()
        #使用urllib和re模块获取博文的评论数和阅读数
        #首先提取存储评论数和点击数网址的正则表达式
        part1 = '<script type="text/javascript" src="(.*?)">'
        #hcurl为存储评论数和点击数的网址
        hcurl = re.compile(part1).findall(str(response.body))[0]
        headers2 = ("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.3964.2 Safari/537.36")
        opener = urllib.request.build_opener()
        opener.addheaders = [headers2]
        urllib.request.install_opener(opener)
        data = urllib.request.urlopen(hcurl).read()
        #pat2为提取文章阅读数的正则表达式
        pat2 = "click\d*?','(\d*?)'"
        #pat3为提取文章评论数的正则表达式
        pat3 = "comment\d*?','(\d*?)'"
        #提取阅读数和评论数数据并分别赋值
        item["hits"] = re.compile(pat2).findall(str(data))
        item["comment"] = re.compile(pat3).findall(str(data))
        yield item
        #提取博文列表页的总页数
        pat4 = "blog.hexun.com/p(.*?)/"
        #通过正则表达式获取到的数据为一个列表,倒数第二个元素为总页数
        data2 = re.compile(pat4).findall(str(response.body))
        if(len(data2) >= 2 ):
            totalurl = data2[-2]
        else:
            totalurl = 1
        #for循环,依次抓取各博文列表页中的数据
        for i in range(2,int(totalurl) + 1):
            #构造下一次爬取的url,爬取一下页博文列表页中的数据
            nexturl = "http://" + str(self.uid) +".blog.hexun.com/p" + str(i) + "/default.html"
            #进行下一次抓取,下一次抓取仍然模拟成浏览器进行
            yield Request(nexturl,callback=self.parse,headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.3964.2 Safari/537.36"})

三、项目结构


四、运行

        在CMD命令行中运行:

                 scrapy crawl myhexunspd --nolog

        在Mysql数据库终端中通过select语句查询运行结果

                select * from myhexun;

五、注意:

1、python和mysql通讯插入数据时,最后需要commit才能将数据提交

2、在phpmysql中查询数据库内容出现中文乱码在mysql中查询无乱码

3、注意代码的正确性,不要打过函数名,函数名打错不容易发现,且报错误不容易看出哪错

4、函数名打错,日志里报的错是函数调用时不能匹配

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值