Python“return self.attrs [key]”错误

bqf10yzr  于 2023-04-04  发布在  Python
关注(0)|答案(1)|浏览(242)

我正在尝试写一个非常简单的python/漂亮的soup脚本

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup 
my_url = 'https://www.travelok.com/listings/sid.1?last_region=&searchFormText=camping'
uclient = uReq(my_url)
page_html = uclient.read()
uclient.close()
filename = "oklahoma_state_parks.csv"
f = open(filename,"w")
headers = "park_name, park_phone, \n"
f.write (headers)
page_soup = soup(page_html, 'html.parser')
containers = page_soup.findAll("article", {"class":"search-result"})

这是测试代码,以确保它在这里工作。

parkinfo_name_test = containers[0].h2.text
parkinfo_phone_test = containers[0].address.div.text

parkinfo_name_test_2 = containers[2].h2.text
parkinfo_phone_test_2 = containers[2].address.div.text

如果我运行代码到这里(上面的所有内容),它工作得很好。我可以打印(parkinfo_name_test)并获得第一个结果。但是当我尝试循环它时-它失败了。当我尝试用代码运行它时,我得到一个错误消息:

for container in containers:
    parkinfo_name = container[0].h2.text
    parkinfo_phone = container[0].address.div.text 

    print ("parkinfo_name: " + parkinfo_name)
    print ("parkinfo_phone " + parkinfo_phone)

    f.write (parkinfo_name + "," + parkinfo_phone + "\n")
    f.close ()

**这是我得到的错误消息:

追溯(最近一次调用):文件“俄克拉荷马州_state_parks.py”,第43行,在parkinfo_name = container[0].h2.text中
File“C:\Users\Myname\AppData\Local\Programs\Python\Python37-32\lib\site-packages\beautifulsoup4-4.6.1-py3.7.egg\bs4\element.py”,line 1071,in __getitem__return self.attrs[key] KeyError:0**

xt0899hw

xt0899hw1#

问题似乎就在这里:

for container in containers:
    parkinfo_name = container[0].h2.text

试着这样做:

for container in containers:
    parkinfo_name = container.h2.text
    parkinfo_phone = container.address.div.text 

    print ("parkinfo_name: " + parkinfo_name)
    print ("parkinfo_phone " + parkinfo_phone)

    f.write (parkinfo_name + "," + parkinfo_phone + "\n")
    f.close ()

相关问题