2017-11-08 17 views
0
import urllib.request 
import bs4 as bs 
import requests 
import re 

url = " https://www.weather-forecast.com/locations/Kansas-City- 
1/forecasts/latest" 
request = requests.get(url) 
response = request.text 

soup = bs.BeautifulSoup(response,'lxml') 

for para in soup.find_all('p'): 

    a = para.text.split('/n') 

    print(a[1]) 

私は例えば印刷しています。リストから94.5Wまでの行だけですが、それは私に範囲外のエラーのインデックスを与えます。 これは私だけ行う場合、私が得る出力されます:複数のリストから特定の行を抽出するインデックスエラー

print(a) 
[''] 
['Kansas City is 232\u2009m above sea level and located at 39.05° N 94.50° 
W. Kansas City has a population of 475378. Local time in Kansas City is 
CST.'] 
['Kansas City 1 – 3 Day Weather Forecast Summary: Mostly dry. Freeze-thaw 
conditions (max 10°C on Wed afternoon, min -2°C on Thu night). Wind will be 
generally light.'] 
[' Local time in Kansas City: CST'] 
['View 3 Hour Detailed Kansas City Weather Forecast for Today'] 
['Kansas City 4 – 7 Day Weather Forecast Summary: Mostly dry. Very mild (max 
12°C on Mon afternoon, min 1°C on Sun night). Winds decreasing (fresh winds 
from the SSW on Sat morning, light winds from the ENE by Sun night).'] 
['Kansas City 7 – 10 Day Weather Forecast Summary: Light rain (total 2mm), 
mostly falling on Wed morning. Very mild (max 17°C on Wed afternoon, min 7°C 
on Thu night). Wind will be generally light.'] 
['© 2017 Meteo365.com'] 

しかし、私は唯一のため、私はあなたがループ内a変数を宣言し、それを印刷している

答えて

0

をしたい特定の行を印刷したいですリストには1つの要素があり、毎回上書きされます。 a宣言とprint()をforループの外に移動すると、そのトリックを行う必要があります

import bs4 as bs 
import requests 
import re 

url = " https://www.weather-forecast.com/locations/Kansas-City-1/forecasts/latest" 
request = requests.get(url) 
response = request.text 

soup = bs.BeautifulSoup(response,'lxml') 

a=[] 
for para in soup.find_all('p'): 

    a.append(para.text.split('/n')) 

print(a[1]) 
関連する問題