2017-12-10 14 views
0

BeautifulSoupを使用して、不動産Webサイトからプロパティのリストリストをスクラップし、それらをデータテーブルに渡そうとしています。私はpython 3を使用しています。BeautifulSoup webすべての 'li'テキストをデータフレームにスクラップ

私は必要なデータを印刷するために働いています。しかし、私はテーブルにデータを出力する方法が必要です。各liタグの間には、3つの項目、プロパティ番号(1〜50)、テナント名と平方フィートがあります。理想的には、出力は列ヘッダー番号、テナント、平方フィートのデータフレームで構成されます。

from bs4 import BeautifulSoup 
import requests 
import pandas as pd 

page = requests.get("http://properties.kimcorealty.com/properties/0014/") 
soup = BeautifulSoup(page.content, 'html.parser') 

start = soup.find('div', {'id' : 'units_box_1'}) 
for litag in start.find_all('li'): 
    print(litag.text) 

start = soup.find('div', {'id' : 'units_box_2'}) 
for litag in start.find_all('li'): 
    print(litag.text) 

start = soup.find('div', {'id' : 'units_box_3'}) 
for litag in start.find_all('li'): 
    print(litag.text) 

答えて

0

あなたはデータの1セットを含む3「LI」タグのグループのために「」タグを囲む見つけ、一度にすべてのdivを取得し、このようにそれを行うことができます。

from bs4 import BeautifulSoup 
import requests 
import unicodedata 
from pandas import DataFrame 

page = requests.get("http://properties.kimcorealty.com/properties/0014/") 
soup = BeautifulSoup(page.content, 'html.parser') 
table = [] 
# Find all the divs we need in one go. 
divs = soup.find_all('div', {'id':['units_box_1', 'units_box_2', 'units_box_3']}) 
for div in divs: 
    # find all the enclosing a tags. 
    anchors = div.find_all('a') 
    for anchor in anchors: 
     # Now we have groups of 3 list items (li) tags 
     lis = anchor.find_all('li') 
     # we clean up the text from the group of 3 li tags and add them as a list to our table list. 
     table.append([unicodedata.normalize("NFKD",lis[0].text).strip(), lis[1].text, lis[2].text.strip()]) 
# We have all the data so we add it to a DataFrame. 
headers = ['Number', 'Tenant', 'Square Footage'] 
df = DataFrame(table, columns=headers) 
print (df) 

出力:

Number       Tenant Square Footage 
0  1     Nordstrom Rack   34,032 
1  2    Total Wine & More   29,981 
2  3   Thomasville Furniture   10,628 
... 
47  49     Jo-Ann Fabrics   45,940 
48  50      Available   32,572 
+0

ありがとうございます!これは完璧です – snappers

関連する問題