@57105710hk

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

Python スクレイピングで複数のclassを取得してCSVに出力したい

解決したいこと

WEBスクレイピングをしているのですが、複数のclassを取得してCSVに出力できず困っています。

発生している問題・エラー

line 7, in <module>
    prices = elems.find('tt01')
AttributeError: 'NoneType' object has no attribute 'find'
上記のエラーが発生します。

コードは下記になります。
import csv
import requests,bs4
res = requests.get('https://www.palcloset.jp/')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text,'html.parser')
elems = soup.find('.textOverflow')
prices = elems.find('tt01')

csvlist = []
for price in prices:
    csvlist.append([elems,prices])

f = open('pal.csv','w',encoding='utf-8')
writecsv = csv.writer(f,lineterminator='\n')

writecsv.writerows(csvlist)

f.close

('.textOverflow')が商品名
('tt01')が価格です。
「商品名、価格」と表示されるCSVの作成方法がわからないです。
大変お手数ですが、ご回答宜しくお願い致します。



0 likes

2Answer

index.py
import requests
from bs4 import BeautifulSoup

output_path = './output.csv'

# windows shift_jis
character_code = "utf-8"

res = requests.get('https://www.palcloset.jp/')
soup = BeautifulSoup(res.text, 'html.parser')

titles = soup.select('.textOverflow')
prices = soup.select('.tt01')

index = 0
with open(output_path, mode='w', encoding=character_code) as f:
    for m in prices:
        _title = titles[index].text.strip()

        _price = m.text.strip()
        _price_replace = _price.replace("¥", "", 1)
        _price_replace = _price_replace.replace(",", "", 1)

        f.write(_title + "," + _price_replace + "\n")
        print(_title)
        print(_price_replace)
        print()

        index += 1
0Like

Your answer might help someone💌