0
我有麻煩數據添加到列表中,我通過迭代
import urllib
import urllib.request
from bs4 import BeautifulSoup
import pandas
def make_soup(url):
thepage = urllib.request.urlopen(url)
thepage.addheaders = [('User-Agent', 'Mozilla/5.0')]
soupdata = BeautifulSoup(thepage, 'html.parser')
return soupdata
soup = make_soup('https://www.wellstar.org/locations/pages/default.aspx')
locationdata = []
for table in soup.findAll('table', class_ = 's4-wpTopTable'):
for name in table.findAll('div', 'PurpleBackgroundHeading'):
name = name.get_text(strip = True)
for loc_type in table.findAll('h3', class_ = 'WebFont SpotBodyGreen'):
loc_type = loc_type.get_text()
for address in table.findAll('div', class_ = ['WS_Location_Address', 'WS_Location_Adddress']):
address = address.get_text(strip = True, separator = ' ')
locationdata.append([name, loc_type, address])
df = pandas.DataFrame(columns = ['name', 'loc_type', 'address'], data = locationdata)
print(df)
產生的數據幀包括所有唯一的地址,但只有最後可能文字對應於name
。
例如,即使'WellStar Windy Hill醫院'是醫院類別/類型中的最後一家醫院,它顯示爲所有醫院的名稱。如果可能,我更喜歡list.append
解決方案,因爲我有幾個類似的步驟來完成此項目。
我覺得這是親密,但是,理想的結果應當包括對每個位置的地址組合loc_type。我們如何能夠將每條記錄的信息包含在內? – Daniel
我給出了將數據放入列表的步驟,但您必須確保從數據頁中提取正確的數據。 – bernie