前提・実現したいこと
htmlデータからExcelへの出力、Excel1列の出力から数列に分離したいのです。
htmlデータからpythonでExcelへの出力をしたいのです。下記プログラムでExcelへの出力をすることはできたのですが、Excelを開くとA列に全て出力されてしまいます。
ExcelのA列に<p class="d-chat_timeline-name"> 名 前(発信者)1 </p>、
ExcelのB列に<ul class="d-chat_timeline-info">
<li>日付と時間1</li>、ExcelのC列に<div>名前1-1(受信者)<br />
名前1-2(受信者)<br />
名前1-3(受信者)<br />
内容1</div>
を出力したいのです。
<htmlデータ>
<div class="d-chat_timeline-post"> <p class="d-chat_timeline-name"> 名 前(発信者)1 </p> <ul class="d-chat_timeline-info"> <li>日付と時間1 </li> </ul> <div>名前1-1(受信者)<br /> 名前1-2(受信者)<br /> 名前1-3(受信者)<br /> 内容1</div>2019/07/12 20:52追記 修正
下記のプログラムを実行しました。
下記のhtmlデータ<p class="d-chat_timeline-name"> 名前</p>はA列の2行目、<ul class="d-chat_timeline-info">日付</li>はB列の14行目、<div>内容</div>はC列の3行目に出力されてしまいます(参照1)。
名前をA列の1行目、日付をB列の1行目、内容をC列の1行目に出力したいのです。コメントアドバイスをお願いいたします。
発生している問題・エラーメッセージ
pythonでのエラーメッセージは出ていません。Excelでの出力を確認すると、ばらばらの行で出力される。
該当のソースコード
python
1# -*- coding: utf-8 -*- 2""" 3Spyderエディタ 4 5これは一時的なスクリプトファイルです 6""" 7 8import os, tkinter, tkinter.filedialog, tkinter.messagebox 9root = tkinter.Tk() 10root.withdraw() 11fTyp = [("","*.html")] 12file = tkinter.filedialog.askopenfilename(filetypes = fTyp) 13fd=open(file,"r",encoding="utf-8") 14 15res=fd.read() 16from bs4 import BeautifulSoup 17 18mojie=[] 19cur_pos=0 20while True : 21 target_tag = '<p class="d-chat_timeline-name">' 22 closing_tag = '</p>' 23 start_pos = res[cur_pos:].find(target_tag) 24 end_pos = res[cur_pos:].find(closing_tag) 25 if (start_pos == -1) or (end_pos == -1): 26 break 27 mojie.append(res[cur_pos + start_pos + len(target_tag) : cur_pos + end_pos]) 28 29 cur_pos = cur_pos + end_pos + len(closing_tag) 30 31 32import xlsxwriter 33wb = xlsxwriter.Workbook('C:/Users/XXXXXXXX/Desktop/out.xlsx') 34ws1 = wb.add_worksheet('sheet') 35 36i=0 37for a in mojie: 38 i=i+1 39 ws1.write(i, 0, a) 40 41mojie=[] 42cur_pos=0 43while True : 44 target_tag = '<ul class="d-chat_timeline-info">' 45 closing_tag = '</li>' 46 start_pos = res[cur_pos:].find(target_tag) 47 end_pos = res[cur_pos:].find(closing_tag) 48 if (start_pos == -1) or (end_pos == -1): 49 break 50 mojie.append(res[cur_pos + start_pos + len(target_tag) : cur_pos + end_pos]) 51 52 cur_pos = cur_pos + end_pos + len(closing_tag) 53 54 55 56i=0 57for a in mojie: 58 i=i+1 59 ws1.write(i, 1, a) 60 61mojie=[] 62cur_pos=0 63while True : 64 target_tag = '<div>' 65 closing_tag = '</div>' 66 start_pos = res[cur_pos:].find(target_tag) 67 end_pos = res[cur_pos:].find(closing_tag) 68 if (start_pos == -1) or (end_pos == -1): 69 break 70 mojie.append(res[cur_pos + start_pos + len(target_tag) : cur_pos + end_pos]) 71 72 cur_pos = cur_pos + end_pos + len(closing_tag) 73 74 75 76i=0 77for a in mojie: 78 i=i+1 79 ws1.write(i, 2, a) 80 81wb.close() 82
試したこと
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/07/12 02:20
2019/07/12 10:21
2019/07/12 12:02 編集
2019/07/12 13:56
2019/07/12 14:07