【发布时间】:2023-04-03 04:31:01
【问题描述】:
如上一个问题所述,我正在使用 Beautiful soup with python 从网站检索天气数据。
网站的外观如下:
<channel>
<title>2 Hour Forecast</title>
<source>Meteorological Services Singapore</source>
<description>2 Hour Forecast</description>
<item>
<title>Nowcast Table</title>
<category>Singapore Weather Conditions</category>
<forecastIssue date="18-07-2016" time="03:30 PM"/>
<validTime>3.30 pm to 5.30 pm</validTime>
<weatherForecast>
<area forecast="TL" lat="1.37500000" lon="103.83900000" name="Ang Mo Kio"/>
<area forecast="SH" lat="1.32100000" lon="103.92400000" name="Bedok"/>
<area forecast="TL" lat="1.35077200" lon="103.83900000" name="Bishan"/>
<area forecast="CL" lat="1.30400000" lon="103.70100000" name="Boon Lay"/>
<area forecast="CL" lat="1.35300000" lon="103.75400000" name="Bukit Batok"/>
<area forecast="CL" lat="1.27700000" lon="103.81900000" name="Bukit Merah"/>`
<channel>
我设法检索了 forecastIssue 日期和有效时间。但是,我无法检索不同区域的预测。
这是我的python代码:
import requests
from bs4 import BeautifulSoup
import urllib3
outfile = open('C:\scripts\idk.xml','w')
#getting the time
r = requests.get('http://www.nea.gov.sg/api/WebAPI/?
dataset=2hr_nowcast&keyref=<keyrefno>')
soup = BeautifulSoup(r.content, "xml")
time = soup.find('validTime').string
print time
#print issue date and time
for currentdate in soup.findAll('item'):
string = currentdate.find('forecastIssue')
print string
这是我要检索区域预测的部分,例如。 area forecast="TL" lat="1.37500000" lon="103.83900000" name="宏茂桥"/
for area in soup.findAll('weatherForecast'):
areastring = area.find('area')
print areastring
当我在 python 中运行我的代码时,它只检索到第一个区域,即宏茂桥
示例输出:
2.30 pm to 5.30 pm
<forecastIssue date="22-07-2016" time="02:30 PM"/>
<area forecast="RA" lat="1.37500000" lon="103.83900000" name="Ang Mo Kio"/>
Inspect element of the website
如你所见,面积预测在div类
如何循环遍历所有区域?我试过谷歌搜索,但显然 findAll 似乎不适用于我的代码
有没有办法拆分日期和时间?
有什么方法可以将 beautifulsoup 检索到的数据解析为 xml 文件?因为我运行代码时的输出不包含任何数据。
谢谢。
【问题讨论】:
-
能否提供上一个问题的链接?
-
至于第 3 点,您对
outfile进行了 0 次写入。自然它不包含任何数据。 -
有什么办法可以将数据输出到outfile?
-
您打算使用什么格式?纯字符串和
outfile.write("some string")一样简单,XML 和其他格式涉及更多。
标签: python beautifulsoup