1. 程式人生 > >爬蟲——爬取網頁資料存入表格

爬蟲——爬取網頁資料存入表格

最近由於個人需要,從相關書籍以及網上資料進行爬蟲自學,目標網址為http://mzj.beijing.gov.cn,對其內容進行整理篩選,存入excel格式。

首先是對錶格的內容進行設定,編碼格式定義為utf-8,新增一個sheet的表格,其中head為表頭的內容,定義之後,利用sheet.write將表頭內容寫入。

book = xlwt.Workbook(encoding='utf-8')
sheet = book.add_sheet('ke_qq')
head = ['組織名稱','登記證號','統一社會信用程式碼','業務主管單位','登記管理機關','社會組織型別','開辦資金','業務範圍','法定代表人','電話','地址','郵編','登記狀態','成立日期','行業分類']#表頭
for h in range(len(head)):
    sheet.write(0,h,head[h])    #寫入表頭

 爬取網頁採用requests進行訪問,利用BeautifulSoup進行解析。

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser', from_encoding='utf-8')

之後提取網頁內容中有效欄位,使用soup.stripped_strings去除其中的空格和空行內容。

str1 = []
    nice = []
    for wz in soup.stripped_strings:
        str1.append(repr(wz))
    k = len(str1)

最後,根據每個人不同的需要,對資料進行整理,在這裡是使用insert、pop、append對資料進行一些調整。

完整程式碼如下:

# coding:utf-8
import requests
from bs4 import BeautifulSoup
import operator as op
import re
import xlwt

user_agent = 'Mozilla/4.0 (compatible;MSIE5.5;windows NT)'
headers = {'User-Agent': user_agent}
num=1
book = xlwt.Workbook(encoding='utf-8')
sheet = book.add_sheet('ke_qq')
head = ['組織名稱','登記證號','統一社會信用程式碼','業務主管單位','登記管理機關','社會組織型別','開辦資金','業務範圍','法定代表人','電話','地址','郵編','登記狀態','成立日期','行業分類']#表頭
for h in range(len(head)):
    sheet.write(0,h,head[h])    #寫入表頭
for one in range(10001,17000):
    keyword = 10000000001
    keywords=keyword+one
    url = 'http://mzj.beijing.gov.cn/wssbweb/wssb/dc/orgInfo.do?action=seeParticular&orgId=0000' + str(keywords) + '&websitId=&netTypeId='
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser', from_encoding='utf-8')
    str1 = []
    nice = []
    for wz in soup.stripped_strings:
        str1.append(repr(wz))
    k = len(str1)
    if k>5:
        i = 1
        for content in str1:
            if i > 3:
                nice.append(content)
            i = i + 1
        try:
            # num=num+1
            if  op.eq(nice[4], '\'業務主管單位:\''):
                nice.insert(4, '無')
            if op.eq(nice[14], '\'法定代表人/負責人:\''):
                nice.insert(14, '無')
            if op.eq(nice[13], '\'活動地域:\''):
                nice.pop(13)
                nice.pop(13)
            if op.eq(nice[16], '\'電話:\''):
                nice.insert(16, '無')
            if op.eq(nice[18], '\'地址:\''):
                nice.insert(18, '無')
            if op.eq(nice[20], '\'郵編:\''):
                nice.insert(20, '無')
            if len(nice)>22:
                if op.eq(nice[22], '\'登記狀態:\''):
                    nice.insert(22, '無')
            if len(nice) > 27:
                if op.eq(nice[27], '\'行業分類:\'') and len(nice) == 28:
                    nice.append('無')
                # if op.eq(nice[13], '\'活動地域:\''):
                #   nice.pop(13)
                #  nice.pop(13)
            if op.eq(nice[12], '\'元\''):
                nice[12] = '0'
            # print(nice)
            j = 0
            d = 0
            s = 0
            for data in nice:
                if j & 1 == 0:
                    s = j - d
                    sheet.write(num, s, data)
                    d += 1
                j += 1
            print(num)
            num += 1
        except:
            print('error'+num)

book.save('E:\WU\pyfile\shuju\save2\shuju2.xls')

其中網頁地址中的keyword由於爬取網頁的不同,可能採取方法有異。