import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class JD_Address
{
private static int timeout = 300000;
private static int count = 0;
public static void main(String[] args) throws IOException, InterruptedException
{
String province_url = "http://trade.jd.com/dynamic/consignee/getProvinces.action";
String city_url = "http://trade.jd.com/dynamic/consignee/getCitys.action?consigneeParam.provinceId=";
String county_url = "http://trade.jd.com/dynamic/consignee/getCountys.action?consigneeParam.cityId=";
String town_url = "http://trade.jd.com/dynamic/consignee/getTowns.action?consigneeParam.countyId=";
//getList(town_url + "4139");
List<Address> provinces = getList(province_url);
for (Address province : provinces)
{
List<Address> citys = getList(city_url + province.getId());
province.setChildren(citys);
for (Address city : citys)
{
List<Address> countys = getList(county_url + city.getId());
city.setChildren(countys);
for (Address county : countys)
{
List<Address> towns = getList(town_url + county.getId());
county.setChildren(towns);
}
}
}
System.out.println("=======");
FileUtils.writeStringToFile(new File("保存位置/address2.js"), "var ds=" + JSON.toJSONString(provinces));
}
private static List<Address> getList(String url) throws IOException, InterruptedException
{
List<Address> list = new ArrayList<Address>();
Document doc = Jsoup.parse(new URL(url), timeout);
Elements elements = doc.select("option[value~=//d+]");
for (Element element : elements)
{
Address address = new Address();
address.setName(element.text().replace("*", StringUtils.EMPTY));
address.setId(element.attr("value"));
list.add(address);
//System.out.println(address.getName());
}
++count;
if (count % 100 == 0)
{
System.out.println(count);
}
if (count % 500 == 0)
{
Thread.sleep(5000);
}
return list;
}
}
class Address
{
private String name;
private String id;
private List<Address> children;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public List<Address> getChildren()
{
return children;
}
public void setChildren(List<Address> children)
{
this.children = children;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
}
JavaScript]代碼