Python开发 之 两种爬虫的方式 正则表达式、XPath

版权声明:本文为博主原创文章,未经博主允许不得转载。作者:沙师弟专栏 https://blog.csdn.net/u014597198/article/details/89404686

1、简介

正在学习python的爬虫,于是爬了一下现在自己的CSDN博客的个人信息。本文讲解了我利用Python3爬取CSDN个人信息的两种方式(正则表达式、XPath)。由于CSDN也会不断的改变它的HTML代码,所以本文只是提供爬取方式哈。

2、简单爬取基本信息——效果图

原图:
在这里插入图片描述
两种效果爬出的效果:
在这里插入图片描述

3、先将一下利用正则的方式

3.1 简单理解

主要用到 urllib 包和 re 包,利用 urllib 包来获取网页信息,再利用 re 包来正则匹配到我想要的字段。是不是很容易?看一下代码吧:

3.2 源码

# !usr/bin/python
# coding: utf-8

import urllib.request
import re

# 当前的博客列表页号
page_num = 1
# 不是最后列表的一页
notLast = []
# 首页地址
baseUrl = "https://shazhenyu.blog.csdn.net/"
# 连接页号,组成爬取的页面网址
myUrl = baseUrl + '/article/list/' + str(page_num)

# 伪装成浏览器访问,直接访问的话csdn会拒绝
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent': user_agent}
# 构造请求
req = urllib.request.Request(myUrl, headers=headers)

# 访问页面
myResponse = urllib.request.urlopen(req)
myPage = myResponse.read()
myPage = myPage.decode("UTF-8")
# print("myPage:",myPage)

# 获取总体信息--利用正则表达式来获取博客的标题
title = re.findall('<title>(.*?)</title>', myPage, re.S)
titleList = []
for items in title:
    titleList.append(str(items).lstrip().rstrip())
print('%s %s' % ('标题;', titleList[0]))

num = re.findall('<a href="https://shazhenyu\.blog\.csdn\.net\?t=1"><span class="count">(.*?)</span></a></dd>', myPage, re.S)
wzList = []
for items in num:
    wzList.append(str(items).lstrip().rstrip())

num = re.findall('<dd><span class="count">(.*?)</span></dd>', myPage, re.S)
numList = []
for items in num:
    numList.append(str(items).lstrip().rstrip())

fan = re.findall('<span class="count" id="fan">(.*?)</span>', myPage, re.S)
fanList = []
for items in fan:
    fanList.append(str(items).lstrip().rstrip())

if len(wzList) > 0:
    print("正则表达式--原创数:",wzList[0])
else:
    print("正则表达式--原创数获取失败,检查是否对方启用了新的匹配规则")
if len(fanList) > 0:
    print("正则表达式--粉丝数:",fanList[0])
else:
    print("正则表达式--粉丝数获取失败,检查是否对方启用了新的匹配规则")
if len(numList) > 1:
    print("正则表达式--喜欢数:",numList[0])
    print("正则表达式--评论数:",numList[1])
else:
    print("正则表达式--喜欢、评论数获取失败,检查是否对方启用了新的匹配规则")

4、XPath

4.1 简单介绍

XPath如何使用,我在:https://shazhenyu.blog.csdn.net/article/details/89218732
这篇文章中提过。只不过那篇文章讲解的是利用Scrapy框架去爬,本文讲的是直接用xpath模块的一种效果。

4.2 源码

# !usr/bin/python
# coding: utf-8

import urllib.request
from lxml import etree

# 当前的博客列表页号
page_num = 1
# 不是最后列表的一页
notLast = []
# 首页地址
baseUrl = "https://shazhenyu.blog.csdn.net/"
# 连接页号,组成爬取的页面网址
myUrl = baseUrl + '/article/list/' + str(page_num)

# 伪装成浏览器访问,直接访问的话csdn会拒绝
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent': user_agent}
# 构造请求
req = urllib.request.Request(myUrl, headers=headers)

# 访问页面
myResponse = urllib.request.urlopen(req)
myPage = myResponse.read()
myPage = myPage.decode("UTF-8")
# print("myPage:",myPage)

html = etree.HTML(myPage)
html_yuanchuang_num = html.xpath('//dl[@class="text-center"]/dd/a/span/text()')
if len(html_yuanchuang_num) == 1:
    print("XPath--原创数:%s"%html_yuanchuang_num[0])
else:
    print("XPath--原创数获取失败,检查是否对方启用了新的匹配规则")
html_info_data = html.xpath('//dl[@class="text-center"]/dd/span/text()')
if len(html_info_data) == 3:
    print("XPath--粉丝数:%s\nXPath--喜欢数:%s\nXPath--评论数:%s\n"%(html_info_data[0],html_info_data[1],html_info_data[2]))
else:
    print("XPath--粉丝、喜欢、评论数获取失败,检查是否对方启用了新的匹配规则")

5、爬取进阶——爬取文章的前10篇的基本信息

5.1 效果图

在这里插入图片描述

5.2 源码

# !usr/bin/python
# coding: utf-8

import urllib.request
from lxml import etree

# 当前的博客列表页号
page_num = 1
# 首页地址
baseUrl = "https://shazhenyu.blog.csdn.net/"
# 连接页号,组成爬取的页面网址
myUrl = baseUrl + '/article/list/' + str(page_num)

# 伪装成浏览器访问,直接访问的话csdn会拒绝
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent': user_agent}
# 构造请求
req = urllib.request.Request(myUrl, headers=headers)

# 访问页面
myResponse = urllib.request.urlopen(req)
myPage = myResponse.read()
myPage = myPage.decode("UTF-8")
# print("myPage:",myPage)

# 把字符串读到html中
html = etree.HTML(myPage)

# 取前n篇文章
artNum = 10

html_info_num = html.xpath('//dl[@class="text-center"]/dd/a/span/text()')
if len(html_info_num) == 1:
    print("XPath--原创数:%s"%html_info_num[0])
else:
    print("XPath--原创数获取失败,检查是否对方启用了新的匹配规则")

html_info_data = html.xpath('//dl[@class="text-center"]/dd/span/text()')
if len(html_info_data) == 3:
    print("XPath--粉丝数:%s\nXPath--喜欢数:%s\nXPath--评论数:%s\n"%(html_info_data[0],html_info_data[1],html_info_data[2]))
else:
    print("XPath--粉丝、喜欢、评论数获取失败,检查是否对方启用了新的匹配规则")

html_artList_name = html.xpath('//div[@class="article-item-box csdn-tracking-statistics"]/h4/a/text()') #文章名称
html_artList_link = html.xpath('//div[@class="article-item-box csdn-tracking-statistics"]/h4/a/@href') #文章链接
html_artList_date = html.xpath('//span[@class="date"]/text()') #文章日期
html_artList_num = html.xpath('//span[@class="num"]/text()') #阅读数、评论数
artList_name = []
artList_link = []
artList_date = []
artList_read = []
artList_pl = []
if len(html_artList_date) > 1:
    if len(html_artList_date) >= 11: #因为第一篇有问题
        for i,item in enumerate(html_artList_link):#文章链接
            if i != 0:
                artList_link.append(item.strip())

        tmpList = []
        for item in html_artList_name:#文章名称
            if item.strip() != "":
                tmpList.append(item)
        for i,item in enumerate(tmpList):
            if i != 0:
                artList_name.append(item.strip())

        for i,item in enumerate(html_artList_date): #文章日期
            if i != 0:
                artList_date.append(item)

        for i,item in enumerate(html_artList_num):#阅读数、评论数
            if i % 2 == 0:
                artList_read.append(item)
            else:
                artList_pl.append(item)

        print("提取前%s篇文章"%artNum)
        for i in range(artNum):
            print("---------------------------------------------------------")
            print("名称:%s\n链接:%s\n时间:%s,阅读数:%s,评论数:%s"%
                  (artList_name[i],artList_link[i],artList_date[i],artList_read[i],artList_pl[i]))
    else:
        print("XPath--文章列表不足10篇")
else:
    print("XPath--文章列表获取失败,检查是否对方启用了新的匹配规则")

猜你喜欢

转载自blog.csdn.net/u014597198/article/details/89404686
今日推荐