用PHP爬取都道府县代码
也许会在未来使用。
PHP的都府县代码列表。
$with_pref_code_as_key_pref_list = array(
'21' => '岐阜県',
'22' => '静岡県',
'23' => '愛知県',
'24' => '三重県',
'25' => '滋賀県',
'26' => '京都府',
'27' => '大阪府',
'28' => '兵庫県',
'29' => '奈良県',
'30' => '和歌山県',
'31' => '鳥取県',
'32' => '島根県',
'33' => '岡山県',
'34' => '広島県',
'35' => '山口県',
'36' => '徳島県',
'37' => '香川県',
'38' => '愛媛県',
'39' => '高知県',
'40' => '福岡県',
'41' => '佐賀県',
'42' => '長崎県',
'43' => '熊本県',
'44' => '大分県',
'45' => '宮崎県',
'46' => '鹿児島県',
'47' => '沖縄県',
);
这将由PHP创建。从Goo邮政编码查询服务中获取。
const rp = require('request-promise');
const cheerio = require('cheerio');
const fs = require('fs');
const options = {
uri: `https://postcode.goo.ne.jp/`,
transform: function (body) {
return cheerio.load(body);
}
};
const get_pref_code_from_href_link = ({
link_txt
}) => {
const splited = link_txt.split('/')
const code_idx = 1
return splited[code_idx]
}
rp(options)
.then(($) => {
const $area_all = $('.area_all')
const $dt = $area_all.find('dt')
const $inner_ul = $area_all.find('ul')
const space_two = ' ';
const space_four = ' ';
let result_txt = '$result = [\n';
$dt.each(function (idx, dt_item) {
// console.log(`地方区分: ${$(dt_item).text()}`)
const regional_classification_name = $(dt_item).text()
result_txt += `${space_two}'${regional_classification_name}' => [\n`
const $target_ul = $($inner_ul[idx])
const $li = $target_ul.find('li')
$li.each(function (idx, li_item) {
const target_a_href = $(li_item).find('a').attr('href');
const pref_code = get_pref_code_from_href_link({
link_txt: target_a_href
})
const pref_name = $(li_item).text()
result_txt += `${space_four}'${pref_code}' => '${pref_name}',\n`
// console.log(`都道府県コード: ${pref_code}`)
})
result_txt += `${space_two}],\n`
})
result_txt += '];'
fs.writeFile('result.txt', result_txt, (err) => {
// throws an error, you could also catch it here
if (err) throw err;
});
})
.catch((err) => {
console.log(err);
});