在遍历以下内容时,无法将数据添加到列表中:
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
解决方案,因为我还有几个类似的步骤要完成这个项目。你知道吗
发生这种情况的原因是,在附加到
locationdata
之前,您正在遍历所有的名称和位置类型。你知道吗您可以改为:
结果:
相关问题 更多 >
编程相关推荐