Beautifulsoup通过HTML循环



如前一个问题所述,我正在使用Beautiful汤和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>

我设法检索到了预测发布日期&有效时间。但是,我无法检索不同区域的预测。

以下是我的python代码:

import requests
from bs4 import BeautifulSoup
import urllib3
outfile = open('C:scriptsidk.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

这是我想要检索区域预报的部分,例如区域预报="TL"lat="1.37500000"lon="103.833900000"name="Ang Mo Kio"//strong>

for area in soup.findAll('weatherForecast'):
areastring = area.find('area')
print areastring

当我在python中运行代码时,它只检索到第一个区域,即Ang Mo Kio

样本输出:

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"/>

检查网站的元素

如您所见,区域预测在div类

  1. 如何循环浏览所有区域?我试过在谷歌上搜索,但显然findAll似乎对我的代码不起作用

  2. 有没有办法把日期和时间分开?

  3. 有什么方法可以将beautifulsoup检索到的数据解析为xml文件吗?因为当我运行代码时,我的输出不包含任何数据。

谢谢。

当我在python中运行代码时,它只检索到第一个区域,即Ang Mo Kio

findAll('weatherForecast')将返回一个元素的序列,给定所提供的XML。然后继续迭代该序列并使用find('area'),它在找到1个元素后停止并返回该元素(如果有的话)。要在天气预报中查找所有区域元素:

for area in soup.find('weatherForecast').find_all('area'):
    print area

有没有办法把日期和时间分开?

不完全确定你的意思,也许你想从元素中提取值:

for currentdate in soup.find_all('item'):
    element = currentdate.find('forecastIssue')
    print element['date'], element['time']

1.要在所有区域中循环,

areas = soup.select('area')
for data in areas:
    print(data.get('name'))

输出

Ang Mo Kio
Bedok
Bishan
Boon Lay
Bukit Batok
Bukit Merah

2.您可以单独提取数据以及

date = soup.select('forecastissue')[0].get('date')
time = soup.select('forecastissue')[0].get('time')

最新更新