可以将数据类型列表更改为bs4.element.ResultSet吗?



我想获得2022-01到2022-04的数据,所以我使用了这个代码。

from urllib.request import urlopen
import pandas as pd
from bs4 import BeautifulSoup
df = []
for i in month:
gu_code = 11680 
numOfRows=1000
month = [202201, 202202, 220203, 202204]

url = "http://openapi.molit.go.kr:8081/OpenAPI_ToolInstallPackage/service/rest/RTMSOBJSvc/getRTMSDataSvcAptTrade?LAWD_CD="+str(gu_code)+"&DEAL_YMD="+ str(i) +"&numOfRows="+str(numOfRows)+"&serviceKey="+str(ServiceKey)
result = urlopen(url) 
house = BeautifulSoup(result, 'lxml-xml')
te = house.find_all('item')
df.append(te)

之后,我使用了这个代码,但问题是df是列表。len(df) = 4

data = []
for i in range(k):
month = df[i].월.string.strip()
price = df[i].거래금액.string.strip()

built_yr = df[i].건축년도.string.strip()

dong_name = df[i].법정동.string.strip()
apt_name = df[i].아파트.string.strip()
size = df[i].전용면적.string.strip()
gu_code = df[i].지역코드.string.strip()

total = [dong_name, apt_name, price, month, built_yr, size, gu_code ]
data.append(total)

如何解决这个问题?

Do:

for i in range(len(df)):

或者更好的方法是将df列表更改为不同的变量,并遍历它:

注意,你的循环没有意义。你正在迭代一个在循环中定义的列表。所以我改变了它,使之有意义,但不知道你在做什么:

from urllib.request import urlopen
import pandas as pd
from bs4 import BeautifulSoup
df_list = []

gu_code = 11680 
numOfRows=1000
month = [202201, 202202, 220203, 202204]
for i in month:

url = "http://openapi.molit.go.kr:8081/OpenAPI_ToolInstallPackage/service/rest/RTMSOBJSvc/getRTMSDataSvcAptTrade?LAWD_CD="+str(gu_code)+"&DEAL_YMD="+ str(i) +"&numOfRows="+str(numOfRows)+"&serviceKey="+str(ServiceKey)
result = urlopen(url) 
house = BeautifulSoup(result, 'lxml-xml')
te = house.find_all('item')
df_list.append(te)

:

data = []
for df in df_list:
month = df[i].월.string.strip()
price = df[i].거래금액.string.strip()

built_yr = df[i].건축년도.string.strip()

dong_name = df[i].법정동.string.strip()
apt_name = df[i].아파트.string.strip()
size = df[i].전용면적.string.strip()
gu_code = df[i].지역코드.string.strip()

total = [dong_name, apt_name, price, month, built_yr, size, gu_code ]
data.append(total)

最新更新