Python BeautifulSoupを使ってスクレイピングしたデータを出力する方法
CSVでの出力
import requests
from bs4 import BeautifulSoup
import csv
head = ["タイトル","値段"]
url = "https://www.gaccom.jp/schools-27344/realestate.html"
res = requests.get(url)
soup = BeautifulSoup(res.text,"html.parser")
with open("sumple.csv","w",encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(head)
for i in soup.select(".side-corner-tag"):
title = i.select(".title-text")[0].string
price = i.select(".large")[0].string
row = [title,price]
w.writerow(row)
↑で同じディレクトリ内にCSVファイルが作成されています。
エクセルでの抽出
import requests
import openpyxl
from bs4 import BeautifulSoup
wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = "スクレイピング"
url = "https://www.gaccom.jp/schools-27344/realestate.html"
res = requests .get(url)
soup = BeautifulSoup(res.text,"html.parser")
cnt = 1
for i in soup.select(".side-corner-tag"):
title = i.select(".title-text")[0].string
price = i.select(".large")[0].string
a = "A"+str(cnt)
b = "B"+str(cnt)
sheet[a].value = title
sheet[b].value = price
cnt += 1
wb.save("sumple.xlsx")
wb.close()
↑で同じディレクトリ内にエクセルファイルが作成されています。