質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.49%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

1回答

1492閲覧

スクレイピングのためのコードが動かない 教えてください。

satsa

総合スコア12

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2019/06/17 12:46

編集2019/06/17 12:55

前提・実現したいこと

pythonの練習で スーモのスクレイピングをしています。
どうやっても動きません。何か根本的に間違いがあるのだと
思いますが、全くわかりません。 教えて頂ければ嬉しいです。

参考サイト:
スーモスクレイピング参考サイト https://akatak.hatenadiary.jp/entry/2018/09/06/220129

発生している問題・エラーメッセージ

name 'info' is not defined name 'subtitle' is not defined 等の以下の定義ができません。 info,subtitle,price,location,station,area,floor_plan,balcony,yrs,link,kanrihi,shuzenhi,stair,direction,reform, total_units, structure, right_form,usage_district,parking 上記の対象をdata[]にappendできません。

該当のソースコード

import requests from bs4 import BeautifulSoup import time import pandas as pd url = 'https://suumo.jp/jj/bukken/ichiran/JJ010FJ001/?ar=030&bs=011&ta=13&jspIdFlg=patternShikugun&sc=13110&kb=1&kt=9999999&mb=0&mt=9999999&ekTjCd=&ekTjNm=&tj=0&cnb=0&cn=9999999&srch_navi=1' result = requests.get(url, timeout=5) c = result.content soup = BeautifulSoup(c, "html.parser") # ページ数を取得 s = soup.find("div", {"class": "pagination pagination_set-nav"}) num_pages = int(s.find_all("a")[-2].string) #.string により()内をstr化して()外により、int化している # [-2]になっておる理由であるが、最終文字列が  次へ になっているために[-2]でないと最終数は取得できない #print(num_pages) #最終ページ数の取得検証 # 全てのページのURLを作成 #num_pages は intにしている urls = [] urls.append(url) for i in range(num_pages-1): pg = str(i+2) url_page = url + '&pn=' + pg urls.append(url_page) #print(urls) #print(urls) ページ生成の検証 for url in urls: k = 0 try: data = [] errors = [] # ここにエンジン部分を記載します。 result = requests.get(url) c = result.content soup = BeautifulSoup(c, "html.parser") summary = soup.find("div",{'id':'js-bukkenList'}) units = summary.find_all("div",{'class':'property_unit'}) #print(units) # ここまでは正常動作確認済 抜き出すスーモURLを変更しても大丈夫 #ここ以下のexceptまでは 挿入位置不明 h2 = units.find_all('h2', {'class':'property_unit-title'}) a = h2.find_all('a') href = a.get('href') link = 'https://suumo.jp' + href + 'bukkengaiyo/' result_child = requests.get(link, timeout=10) c_child = result_child.content soup_child = BeautifulSoup(c_child, "html.parser") summary_child = soup_child.find_all('tbody', {'class':'vat tal'}) #summary_childは、更に次の物件概要の定義になっている summary=概要の意味 # ここまでは正常動作確認済 抜き出すスーモURLを変更しても大丈夫 try: info = units.find('span',{'class':'ui-label ui-label--cta1 ui-label--cta4'}).string except: pass # 物件名 subtitle = units.find('dd',{'class':'dottable-vm'}).string # 価格 price = units.find('span',{'class':'dottable-value'}).string # 住所 location = units.find_all('dd')[2].string # 最寄駅 station = units.find_all('dd')[3].string # 専有面積 area = units.find_all('dd')[4].contents[0].split('m')[0] # 間取り floor_plan = units.find_all('dd')[5].string # バルコニー balcony = units.find_all('dd')[6].contents[0].split('m')[0] # 築年月 yrs = units.find_all('dd')[7].string # link link = units.find('h2',{'class':'property_unit-title'}).a.get('href') # 管理費 kanrihi = summary_child[0].find_all('td')[5].string.strip('\r\n\t') # 修繕積立費 shuzenhi = summary_child[0].find_all('td')[6].string.strip('\r\n\t') # 物件階 stair = summary_child[0].find_all('td')[14].string.strip('\r\n\t') # 方角 direction = summary_child[0].find_all('td')[15].string.strip('\r\n\t') # リフォーム reform = summary_child[0].find_all('td')[16].contents # 総戸数 total_units = summary_child[1].find_all('td')[2].string.strip('\r\n\t') # 構造・階建て structure = summary_child[1].find_all('td')[3].string.strip('\r\n\t') # 権利形態 right_form = summary_child[1].find_all('td')[5].string.strip('\r\n\t') # 用途地域 usage_district = summary_child[1].find_all('td')[6].string.strip('\r\n\t') # 駐車場 parking = summary_child[1].find_all('td')[7].string.strip('\r\n\t') # カテゴリ分けサブタイトルの後ろに来るはずのexcept公文 data.append([info,subtitle,price,location,station,area,floor_plan,balcony,yrs,link,kanrihi,shuzenhi,stair,direction,reform, total_units, structure, right_form,usage_district,parking]) except Exception as e: errors.append([e, url, k,subtitle]) pass # data listを DataFrameに変換 df = pd.DataFrame(data, columns=['情報','物件名','価格','住所','最寄駅','専有面積','間取り','バルコニー','築年月','リンク','管理費', '修繕積立費','物件階', '方角','リフォーム','総戸数', '構造・階建て','権利形態','用途地域','駐車場']) # csvファイルとして保存 #参考ソースから/Dataは消した df.to_csv('suumo_used_mansion3.csv', sep = ',',encoding='utf-8') # ついでに errors fileも保存 df_errors = pd.DataFrame(errors) #参考ソースからファイルパスの/Dataは消した df_errors.to_csv('errors_used_mansion.csv', sep = ',', encoding='utf-8')

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hayataka2049

2019/06/17 12:51

質問文を編集して、<code>ボタンで挿入できるコードブロックの中にコードを入れてください。そうしないと読めません。
guest

回答1

0

units = summary.find_all("div",{'class':'property_unit'})

上記でunitsは配列になっているかと思います。
それに対して、下記でfindを呼んでいるのがエラーの原因ではないでしょうか?

try:
info = units.find('span',{'class':'ui-label ui-label--cta1 ui-label--cta4'}).string

エラー詳細が不明なため、見当違いでしたらすみません。

投稿2019/07/27 14:33

meg_

総合スコア10579

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.49%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問