【发布时间】:2020-07-21 04:49:06
【问题描述】:
import pandas as pd
import requests
from bs4 import BeautifulSoup
page = requests.get("https://forecast.weather.gov/MapClick.php?lat=40.71455000000003&lon=-74.00713999999994#.XxWVcSgzbIU")
soup = BeautifulSoup(page.content, 'html.parser')
week = soup.find(id='seven-day-forecast-list')
items = week.find_all(class_='tombstone-container')
'''
print(items[1].find(class_='period-name').get_text())
print(items[1].find(class_='short-desc').get_text())
print(items[1].find(class_='temp').get_text())
'''
#doing the above with list comprehesion
while(1):
period_names=[item.find(class_='period-name').get_text() for item in items]
short_descrpition=[item.find(class_='short-desc').get_text() for item in items]
temp_names=[item.find(class_='temp').get_text() for item in items]
weather_stuff = pd.DataFrame({
'period':period_names,
'short_descrpition': short_descrpition,
'temperature':temp_names,
})
weather_stuff.to_csv('weather.csv')
我可以使用 while(1) 继续更新 weather.csv 文件,直到我中断程序吗?
【问题讨论】:
-
为了不断更新,您需要不断向网站发送请求。
标签: python python-3.x web-scraping