import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Arrays;


public class Weather {
 String urlString;
 String array;
 StringBuffer sb=new StringBuffer("");
  
 public static void main(String[] args) throws Exception {
  Weather client = new Weather("http://www.weather.com.cn/weather/101181201.shtml");
  client.run();
 }
 public Weather(String urlString) {
  this.urlString = urlString;
 }
 public void run() throws Exception {
 
  URL url = new URL(urlString);
  
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  
  BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection
    .getInputStream(),"utf8"));
  String line;

  while ((line = reader.readLine()) != null){
  Pattern p = Pattern.compile("<p class=\"wea\">(.+?)</p>");
    Matcher m = p.matcher(line);
    while(m.find()) { 
        array = m.group(1);
        sb.append(array+","); 
    }
  }
  
    String arr = sb.toString();
    String[] s = arr.split("\\,");
    System.out.println(s[s.length - 7]);
    
 }
 

}

 

utf8编码格式

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Arrays;


public class Weather {
 String urlString;
 String array;
 StringBuffer sb=new StringBuffer("");
  
 public static void main(String[] args) throws Exception {
  
  Weather client = new Weather("http://www.weather.com.cn/weather/101181201.shtml");
  client.run();
 }
 public Weather(String urlString) {
  this.urlString = urlString;
 }
 public void run() throws Exception {
 
  URL url = new URL(urlString);
  
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  
  BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection
    .getInputStream(),"utf8"));
  String line;

  while ((line = reader.readLine()) != null){
  Pattern p = Pattern.compile("<p class=\"wea\">(.+?)</p>");
    Matcher m = p.matcher(line);
    while(m.find()) { 
        array = m.group(1);
        sb.append(array+",");//符合正则的数据追加到sb,并以逗号分割 
    }
  }
  
    String arr = sb.toString();//sb转为字符串
    String[] s = arr.split("\\,");//字符串转为数组,以逗号为标记 
    System.out.println(s[s.length - 7]);//取数组中倒数第7个数
    
 }
 

}

 

相关文章:

  • 2021-06-11
  • 2021-12-04
  • 2022-01-22
  • 2021-06-24
  • 2022-01-23
  • 2022-02-09
  • 2021-08-08
猜你喜欢
  • 2022-12-23
  • 2021-05-24
  • 2022-02-07
  • 2021-11-19
  • 2021-09-20
相关资源
相似解决方案