小彩蛋 设置数据表主键的自增起始值
alter table 数据表名字 auto_increment = 起始值;
作业回顾
<?php
require 'vendor/autoload.php';
use Medoo\Medoo;
use QL\QueryList;
$ql = new QueryList();
$database = new Medoo([
'database_type' => 'mysql',
'database_name' => 'bookstore',
'server' => 'localhost',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
]);
function get_category($url) {
global $ql;
$data = $ql->get($url)->rules([
"category_name" => ['#default > div > div > div > aside > div.side_categories > ul > li > ul > li > a', 'text'],
"category_url" => ['#default > div > div > div > aside > div.side_categories > ul > li > ul > li > a', 'href'],
])->queryData();
foreach ($data as $key => $value) {
$value['category_url'] = $url . $value['category_url'];
$data[$key] = $value;
}
return $data;
}
function get_book($url) {
global $ql;
echo $url . "\n";
$data = $ql->get($url)->rules([
"book_name" => ['#default > div > div > div > div > section > div:nth-child(2) > ol > li > article > h3 > a', 'title'],
"book_price" => ['#default > div > div > div > div > section > div:nth-child(2) > ol > li> article > div.product_price > p.price_color', 'text'],
])->queryData();
$next = has_next($url);
if ($next) {
$tmp_arr = explode('/', $url);
$tmp_arr[count($tmp_arr) - 1] = $next;
$next_url = implode('/', $tmp_arr);
$data = array_merge($data, get_book($next_url));
}
return $data;
}
function has_next($url) {
global $ql;
$res = $ql->get($url)->find('#default > div > div > div > div > section > div:nth-child(2) > div > ul > li.next > a')->href;
return $res;
}
function make_array($data) {
foreach ($data as $key => $value) {
$value['books'] = get_book($value['category_url']);
$data[$key] = $value;
}
return $data;
}
function save_data($data) {
foreach ($data as $key => $value) {
$bcid = create_category($value['category_name']);
foreach ($value['books'] as $k => $book) {
$bname = $book['book_name'];
$bprice = $book['book_price'];
create_book($bname, $bprice, $bcid);
}
}
}
function create_category($category_name) {
global $database;
$id = $database->insert('category', [
'cname' => $category_name
]);
return $database->id();
}
function create_book($bname, $bprice, $bcid) {
global $database;
$database->insert('book', [
'bname' => $bname,
'bprice' => $bprice,
'bcid' => $bcid,
]);
}
$data = make_array(get_category('http://books.toscrape.com/'));
save_data($data);
最终效果
下一节