在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ python爬蟲數(shù)據(jù)存儲(chǔ)到excel

python爬蟲數(shù)據(jù)存儲(chǔ)到excel

爬取了騰訊課堂的一些數(shù)據(jù),但是在存儲(chǔ)的過程中遇到了一點(diǎn)問題。就是無法正確地存儲(chǔ)到相對(duì)應(yīng)的行和列,
下面是代碼:

import requests
import re
from bs4 import BeautifulSoup
import xlwt             #導(dǎo)入相關(guān)庫
 
all_info_list = []      #定義一個(gè)空列表,用來存儲(chǔ)爬蟲數(shù)據(jù)。
 
headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.74 Safari/537.36'}         #請(qǐng)求頭
 
def get_info(url):
    res = requests.get(url,headers = headers)
    soups = BeautifulSoup(res.text, "lxml").find_all('h4')
    for soup in soups:
        infos= soup.find_all('a')
        for info in infos:
            course = re.findall(r'(?<=title=").*?(?=")', str(info))      #課程
            href = re.findall(r'(?<=href=").*?(?=")',str(info))          #鏈接
    firms = re.findall(r'<span class="item-source">(.*?)</span>', res.text, re.S)
    firm = re.findall(r'(?<=title=").*?(?=")', str(firms))               #出品
    info_list = [course, href, firm]
    all_info_list.append(info_list)                     #寫入爬蟲數(shù)據(jù)
 
if __name__ == "__main__":          #主函數(shù)
    urls = ['https://ke.qq.com/course/list?mt=1001&st=2002&tt=3019&page={}'.format(i) for i in range(1,10)]
    for url in urls:
        get_info(url)
 
    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])    #寫入表頭
    i = 1
    for list in all_info_list:
        j = 0
        for data in list:
            sheet.write(i,j,data)
            j+=1
        i+=1
book.save('E:\spiderfile\ke.xls')

結(jié)果如圖:
圖片描述

請(qǐng)問如何正確存儲(chǔ)數(shù)據(jù)

回答
編輯回答
厭惡我

為什么不嘗試一下直接保存為xxx.csv格式的文件呢,.csv屬于純文本文件,而且可以用excel直接打開,它的格式如下:
1 開頭是不留空,以行為單位。
2 可含或不含列名,含列名則居文件第一行。
3 一行數(shù)據(jù)不跨行,無空行。
4 以半角逗號(hào)(即,)作分隔符,列為空也要表達(dá)其存在。
5 列內(nèi)容如存在半角引號(hào)(即"),替換成半角雙引號(hào)("")轉(zhuǎn)義,即用半角引號(hào)(即"")將該字段值包含起來。
6 文件讀寫時(shí)引號(hào),逗號(hào)操作規(guī)則互逆。
7 內(nèi)碼格式不限,可為 ASCII、Unicode 或者其他。
8 不支持特殊字符

2018年3月16日 18:27
編輯回答
鹿惑

把這段代碼

firms = re.findall(r'<span class="item-source">(.*?)</span>', res.text, re.S)
firm = re.findall(r'(?<=title=").*?(?=")', str(firms))               #出品
info_list = [course, href, firm]
all_info_list.append(info_list)                     #寫入爬蟲數(shù)據(jù)

放在

for soup in soups:

循環(huán)里面。

2018年1月1日 09:13