温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python爬虫实例分析

发布时间:2022-01-18 14:31:22 来源:亿速云 阅读:122 作者:iii 栏目:编程语言

今天小编给大家分享一下Python爬虫实例分析的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

环境搭建

既然用python,那么自然少不了语言环境。于是乎到官网下载了3.5版本的。安装完之后,随机选择了一个编辑器叫PyCharm,话说python编辑器还真挺多的。

发送请求

当然我不知道python是怎么进行网络请求的,其中还有什么2.0和3.0的不同,中间曲曲折折了不少,最终还是写出了最简单的一段请求代码。

import urllib.parse

import urllib.request

 

# params  CategoryId=808 CategoryType=SiteHome ItemListActionName=PostList PageIndex=3 ParentCategoryId=0 TotalPostCount=4000

def getHtml(url,values):

    user_agent='Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36'

    headers = {'User-Agent':user_agent}

    data = urllib.parse.urlencode(values)

    response_result = urllib.request.urlopen(url+'?'+data).read()

    html = response_result.decode('utf-8')

    return html

 

#获取数据

def requestCnblogs(index):

    print('请求数据')

    url = 'http://www.cnblogs.com/mvc/AggSite/PostList.aspx'

    value= {

         'CategoryId':808,

         'CategoryType' : 'SiteHome',

         'ItemListActionName' :'PostList',

         'PageIndex' : index,

         'ParentCategoryId' : 0,

        'TotalPostCount' : 4000

    }

    result = getHtml(url,value)

    return result

其实博客园这个请求还是挺标准的,哈哈正好适合抓取。因为他返回的就是一段html。(如果返回json那不是更好。。。。)

数据解析

上文已经提到了,用到的是BeautifulSoup,好处就是不用自己写正则,只要根据他的语法来写就好了,在多次的测试之后终于完成了数据的解析。先上一段HTML。然后在对应下面的代码,也许看起来更轻松一些。

<div class="post_item">

    <div class="digg">

        <div class="diggit" onclick="DiggPost('hyper-xl',6417741,281238,1)">

            <span class="diggnum" id="digg_count_6417741">1</span>

        </div>

        <div class="clear"></div>

        <div id="digg_tip_6417741" class="digg_tip"></div>

    </div>

    <div class="post_item_body">

        <h4><a class="titlelnk" href="http://www.cnblogs.com/hyper-xl/p/6417741.html" target="_blank">Python 字符串格式化</a></h4>

 

 

        <p class="post_item_summary">

            <a href="http://www.cnblogs.com/hyper-xl/" target="_blank">

                <img width="48" height="48" class="pfs"

                     src="//pic.cnblogs.com/face/795666/20160421231717.png" alt="" />

            </a>    转载请注明出处 Python2.6+ 增加了str.format函数,用来代替原有的'%'操作符

 

            。它使用比'%'更加直观、灵活。下面详细介绍一下它的使用方法。 下面是使用'%'的例子: 格式很像C语言的printf是不是?由于'%'是一个操作符,只能在左右

 

            两边各放一个参数,因此右边多个值需要用元组或 ...

        </p>

 

        <div class="post_item_foot">

            <a href="http://www.cnblogs.com/hyper-xl/" class="lightblue">新月的力量_141</a>

            发布于 2017-02-19 23:07

            <span class="article_comment">

                <a href="http://www.cnblogs.com/hyper-xl/p/6417741.html#commentform" title="" class="gray">

                    评论(0)

                </a>

            </span>

            <span class="article_view">

                <a href="http://www.cnblogs.com/hyper-xl/p/6417741.html" class="gray">

                    阅读

 

                    (138)

                </a>

            </span>

        </div>

    </div>

    <div class="clear"></div>

</div>

通过上文的HTML代码可以看到几点。首先每一条数据都在 div(class=”post_item”)下。然后 div(“post_item_body”)下有用户信息,标题,链接,简介等信息。逐一根据样式解析即可。代码如下:厦门租叉车公司

from bs4 import BeautifulSoup

import request

import re

 

#解析最外层

def blogParser(index):

 

  cnblogs = request.requestCnblogs(index)

  soup = BeautifulSoup(cnblogs, 'html.parser')

  all_div = soup.find_all('div', attrs={'class': 'post_item_body'}, limit=20)

 

  blogs = []

  #循环div获取详细信息

  for item in all_div:

      blog = analyzeBlog(item)

      blogs.append(blog)

 

  return blogs

 

#解析每一条数据

def analyzeBlog(item):

    result = {}

    a_title = find_all(item,'a','titlelnk')

    if a_title is not None:

        # 博客标题

        result["title"] = a_title[0].string

        # 博客链接

        result["href"] = a_title[0]['href']

    p_summary = find_all(item,'p','post_item_summary')

    if p_summary is not None:

        # 简介

        result["summary"] = p_summary[0].text

    footers = find_all(item,'div','post_item_foot')

    footer = footers[0]

    # 作者

    result["author"] = footer.a.string

    # 作者url

    result["author_url"] = footer.a['href']

    str = footer.text

    time = re.findall(r"发布于 .+? .+? ", str)

    result["create_time"] = time[0].replace('发布于 ','')

 

    comment_str = find_all(footer,'span','article_comment')[0].a.string

    result["comment_num"] = re.search(r'\d+', comment_str).group()

 

    view_str = find_all(footer,'span','article_view')[0].a.string

    result["view_num"] = re.search(r'\d+', view_str).group()

 

    return result

 

def find_all(item,attr,c):

    return item.find_all(attr,attrs={'class':c},limit=1)

上边一堆代码下来,着实花费了我不少时间,边写边调试,边百度~~不过还好最终还是出来了。等数据都整理好之后,然后我把它保存到了txt文件里面,以供其他语言来处理。本来想写个put直接put到ElasticSearch中,奈何没成功。后边在试吧,毕竟我的重点只是导数据,不在抓取这里。

import match

import os

import datetime

import json

 

def writeToTxt(list_name,file_path):

    try:

        #这里直接write item 即可,不要自己给序列化在写入,会导致json格式不正确的问题

        fp = open(file_path,"w+",encoding='utf-8')

        l = len(list_name)

        i = 0

        fp.write('[')

        for item in list_name:

            fp.write(item)

            if i<l-1:

                fp.write(',\n')

            i += 1

        fp.write(']')

        fp.close()

    except IOError:

        print("fail to open file")

 

#def getStr(item):

#   return json.dumps(item).replace('\'','\"')+',\n'

 

def saveBlogs():

    for i in range(1,2):

        print('request for '+str(i)+'...')

        blogs = match.blogParser(i,5)

        #保存到文件

        path = createFile()

        writeToTxt(blogs,path+'/blog_'+ str(i) +'.json')

        print('第'+ str(i) +'页已经完成')

    return 'success'

 

def createFile():

    date = datetime.datetime.now().strftime('%Y-%m-%d')

    path = '/'+date

    if os.path.exists(path):

        return path

    else:

        os.mkdir(path)

        return path

 

result = saveBlogs()

print(result)

以上就是“Python爬虫实例分析”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI