所以我是 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 变量的长度,因为它可能太短了。
