所以我是python的新手,我写了一段代码,可以在网站上显示全英国房屋的平均价格,但它很难适用于列表>;5。这通常是由于网站,因为当我再次点击它的作品…但只有有时。你知道吗
price变量以前是一个很长的语句,但它总是出错,所以我将它拆分为for语句,这个语句不断出现:
Traceback (most recent call last):
File "airbnb.py", line 18, in <module>
town = item [i]
File "//anaconda/lib/python3.5/site-packages/bs4/element.py", line 997, in __getitem__
return self.attrs[key]
KeyError: 1
这是我的全部代码:
df = pd.read_csv('towns.csv')
item=df.test
name=[]
l1=[]
date=[]
for i in range(len(item)):
town = item [i]
url='https://www.airbnb.co.uk/s/?page=1&source=filters&airbnb_plus_only=false&room_types%5B%5D=Entire%20home%2Fapt&ss_id=6eaibfgb&allow_override%5B%5D=&s_tag=QmOEOer6'
index=url.find('?page=')
url=url[:index] + str(town) + url[index:]
r=requests.get(url)
soup=BeautifulSoup(r.content,'lxml')
price=(soup.find('div',{"class":"avg-price"}))
for item in price:
j=(soup.find('span',{"class":"price"}).text)
j=j [1:][:3]
l1.append(j)
name.append(town)
time.sleep(1)
stamp=time.strftime('%x')
date.append(stamp)
print(town)
print(l1)
print(date)
我认为错误在于
j=j [1:][:3]
我建议在执行此操作之前检查j变量的长度,因为它可能太短。你知道吗相关问题 更多 >
编程相关推荐