Summary
ホームページから、playwright で 2次元テーブルデータを取得する
JSONの取得方法
たとえば2次元表を下記のジャバスクリプトで取得してみる
() => {
const table = document.querySelector('table > tbody');
return Array.from(table.rows).map((row) =>
[
{
くだもの名: row.cells[0].textContent
, 価格 : row.cells[1].textContent
, 備考 : row.cells[2].textContent
}
]);
}
playwrightでF#に取り込む
// dic's key を指定しやすくする
type Fruits =
| くだもの名
| 価格
| 備考
with
member this.s = this.ToString()
// テーブルの骨格(デシリする際に必要)
type T = {|
a:{|
o:{|
k:string
v:{|s:string|}
|}[]
|}[]
|}
// JSONをdicに変換する
let tableBodyRows (body: JsonElement) =
body.EnumerateArray()
|> Seq.map (fun (x:JsonElement) ->
printfn "%A" x
JsonSerializer.Deserialize<T>(x)
|> fun x -> x.a
|> Array.map(fun y -> y.o)
|> Array.map(fun x -> x |> Array.map(fun x -> seq{x.k,x.v.s} ) )
|> Array.exactlyOne
|> Seq.concat
|> dict
)
// 処理本体
task {
let! page = page
let! content = page.EvaluateAsync(javascriptCode)
content.Value |> tableBodyRows
|> Seq.iter(fun dic ->
dic.Item Tbl.くだもの名.s |> printfn "%s"
)
}
おまけ
ホームページからJSONラベル指定せずにとりこむ
// JSONの骨格
type U = {|
a:{|
s:string
|}[]
|}
// JSON -> fsharp collection
let tableBodyRows (body:JsonElement) =
body.EnumerateArray()
|> Seq.map (fun (x:JsonElement) ->
x
|> JsonSerializer.Deserialize<U>
|> fun x -> x.a
|> Array.map(fun y -> y.s)
)