【发布时间】:2019-06-10 18:33:18
【问题描述】:
当我运行我的代码并在我的 for 循环中添加打印语句时,邮政编码、城市和地区会正确打印出第一个邮政编码,但它永远不会进入我的下一个邮政编码。当我打印出我的 DataFrame 时,所有值都设置为 NaN。
我尝试运行一个通用的 for 循环来在 PyCharm 中分别打印每个邮政编码,它只打印第一个邮政编码,但是当我在 Jupyter Notebook 中运行相同的代码时,每个邮政编码都会打印出来
for z in zipcodes:
# gets the website to find the closest big city
res = requests.get('https://www.travelmath.com/cities-near/' + z)
soup = bs4.BeautifulSoup(res.text, 'html.parser')
elems = soup.select('#EchoTopic > div:nth-child(1) > ul:nth-child(8) > li:nth-child(1) > a:nth-child(2)')
place = elems[0].text.strip()
city, state = place.split(',')
# uses the city found above to find the text in the webpage and the region it corresponds to
newres = requests.get('https://www.almanac.com/weather/longrange')
newsoup = bs4.BeautifulSoup(newres.text, 'html.parser')
newelems = newsoup.find('td', text=city).parent.parent
alltext = newelems.text
region = find_region(alltext) # helper regex function I wrote
# appends the zip code, city, and region to the DataFrame
regions.append([z, city, region])
只打印出第一个邮政编码、城市和地区,并返回一个 NaN 的 DataFrame,而不是打印出近 4,000 个邮政编码及其相关信息,并且不将任何信息写入 DataFrame
【问题讨论】:
标签: python-3.x pandas dataframe beautifulsoup