pandasのCSV出力に関して質問させて頂きます。
行いたい内容
スクレイピングで抽出した複数の要素を格納した関数をpandasでCSV出力する際、複数行で出力したい。
処理の流れ
- BeautifulSoupで<script></script>内を取得
- 取得した要素をhttp jpgで分割
- 分割した要素をimg_urlに格納
- pandasでimg_urlをcsvで出力
現状のコード
Python
1import urllib.request 2import pandas as pd 3from bs4 import BeautifulSoup 4from selenium import webdriver 5 6driver = webdriver.Chrome ( executable_path=r'C:\Users\chromedriver_win32\chromedriver.exe' ) 7driver.get ("https://hogehoge.com" ) 8 9html = driver.page_source 10bs = BeautifulSoup ( html, "html.parser" ) 11 12for script_ele in bs.find_all ( "script" ): 13 text_list = str(script_ele).split("\"")# 引用符「"」で分割 14 for img_url in text_list: 15 if img_url.startswith("http") and img_url.endswith("jpg"): 16 print (img_url) 17 Datef = pd.DataFrame([ 18 ["A", "B", (img_url),],], 19 columns=['Title', 'Body (HTML)', 'Image Src', ]) 20Datef.to_csv('C:/Users/csv_out.csv',encoding='cp932')
img_urlに格納されている要素
https://hogehoge.com/hogehoge.jpg
https://hogehoge.com/hogehoge1.jpg
https://hogehoge.com/hogehoge2.jpg
https://hogehoge.com/hogehoge3.jpg
https://hogehoge.com/hogehoge4.jpg
https://hogehoge.com/hogehoge5.jpg
現状の出力状況
Title | Body (HTML) | Image Src |
---|---|---|
A | B | https://hogehoge.com/hogehoge5.jpg |
※何故か、一番最後の要素が出力されます。
行いたい出力形式
最後に
以上の出力がそもそも出来るのか、出来ないのか、できるのであればどうすれば出来るのか皆様のお力をお貸し頂けますと幸いです。
お願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/25 07:13 編集
2020/01/25 07:20
2020/01/25 07:37