溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python爬蟲(chóng)實(shí)例分析

發(fā)布時(shí)間:2022-01-18 14:31:22 來(lái)源:億速云 閱讀:132 作者:iii 欄目:編程語(yǔ)言

今天小編給大家分享一下Python爬蟲(chóng)實(shí)例分析的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來(lái)了解一下吧。

環(huán)境搭建

既然用python,那么自然少不了語(yǔ)言環(huán)境。于是乎到官網(wǎng)下載了3.5版本的。安裝完之后,隨機(jī)選擇了一個(gè)編輯器叫PyCharm,話說(shuō)python編輯器還真挺多的。

發(fā)送請(qǐng)求

當(dāng)然我不知道python是怎么進(jìn)行網(wǎng)絡(luò)請(qǐng)求的,其中還有什么2.0和3.0的不同,中間曲曲折折了不少,最終還是寫出了最簡(jiǎn)單的一段請(qǐng)求代碼。

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

 

#獲取數(shù)據(jù)

def requestCnblogs(index):

    print('請(qǐng)求數(shù)據(jù)')

    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

其實(shí)博客園這個(gè)請(qǐng)求還是挺標(biāo)準(zhǔn)的,哈哈正好適合抓取。因?yàn)樗祷氐木褪且欢蝖tml。(如果返回json那不是更好。。。。)

數(shù)據(jù)解析

上文已經(jīng)提到了,用到的是BeautifulSoup,好處就是不用自己寫正則,只要根據(jù)他的語(yǔ)法來(lái)寫就好了,在多次的測(cè)試之后終于完成了數(shù)據(jù)的解析。先上一段HTML。然后在對(duì)應(yīng)下面的代碼,也許看起來(lái)更輕松一些。

<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>    轉(zhuǎn)載請(qǐng)注明出處 Python2.6+ 增加了str.format函數(shù),用來(lái)代替原有的'%'操作符

 

            。它使用比'%'更加直觀、靈活。下面詳細(xì)介紹一下它的使用方法。 下面是使用'%'的例子: 格式很像C語(yǔ)言的printf是不是?由于'%'是一個(gè)操作符,只能在左右

 

            兩邊各放一個(gè)參數(shù),因此右邊多個(gè)值需要用元組或 ...

        </p>

 

        <div class="post_item_foot">

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

            發(fā)布于 2017-02-19 23:07

            <span class="article_comment">

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

                    評(píng)論(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>

通過(guò)上文的HTML代碼可以看到幾點(diǎn)。首先每一條數(shù)據(jù)都在 div(class=”post_item”)下。然后 div(“post_item_body”)下有用戶信息,標(biāo)題,鏈接,簡(jiǎn)介等信息。逐一根據(jù)樣式解析即可。代碼如下:廈門租叉車公司

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 = []

  #循環(huán)div獲取詳細(xì)信息

  for item in all_div:

      blog = analyzeBlog(item)

      blogs.append(blog)

 

  return blogs

 

#解析每一條數(shù)據(jù)

def analyzeBlog(item):

    result = {}

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

    if a_title is not None:

        # 博客標(biāo)題

        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:

        # 簡(jiǎn)介

        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"發(fā)布于 .+? .+? ", str)

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

 

    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)

上邊一堆代碼下來(lái),著實(shí)花費(fèi)了我不少時(shí)間,邊寫邊調(diào)試,邊百度~~不過(guò)還好最終還是出來(lái)了。等數(shù)據(jù)都整理好之后,然后我把它保存到了txt文件里面,以供其他語(yǔ)言來(lái)處理。本來(lái)想寫個(gè)put直接put到ElasticSearch中,奈何沒(méi)成功。后邊在試吧,畢竟我的重點(diǎn)只是導(dǎo)數(shù)據(jù),不在抓取這里。

import match

import os

import datetime

import json

 

def writeToTxt(list_name,file_path):

    try:

        #這里直接write item 即可,不要自己給序列化在寫入,會(huì)導(dǎo)致json格式不正確的問(wèn)題

        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) +'頁(yè)已經(jīng)完成')

    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爬蟲(chóng)實(shí)例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI