回答編集履歴

2

訂正

2020/12/02 10:25

投稿

nto
nto

スコア1438

test CHANGED
@@ -70,9 +70,9 @@
70
70
 
71
71
  rowspanを抽出し、rowspanが1を超える場合には
72
72
 
73
- rowspanの数だけ`.find_next_siblings()`を取得し
73
+ `.find_next_siblings()`で兄弟要素を取得し
74
74
 
75
- 先頭列に[機械種別]の記載がないデータの数(列×2行)のデータをスライスして抽出しています。
75
+ 先頭列に[機械種別]の記載がないデータの数(列(rowspan-1)×2行)のデータをスライスして抽出しています。
76
76
 
77
77
  抽出したデータの先頭に保持していたgenre変数(機械種別名)をおいてデータを整形し
78
78
 

1

追記

2020/12/02 10:25

投稿

nto
nto

スコア1438

test CHANGED
@@ -49,3 +49,93 @@
49
49
  df.to_csv('result.csv', encoding='cp932', header=header, index=False)
50
50
 
51
51
  ```
52
+
53
+
54
+
55
+ ### 追記
56
+
57
+ とりあえずは以下で目的の形での取得が可能かと思います。
58
+
59
+ ちょっと複雑で説明が難しいです。
60
+
61
+ for文ではenumerarteで何番目かを判定しています。
62
+
63
+ 0番目(初回)のループである場合にはヘッダー行は無視し
64
+
65
+ それ以外の場合には要素をtd要素を抽出します。
66
+
67
+
68
+
69
+ 今回のソースの場合[機械種別]が記載されたtrにrowspanが設定されていた為
70
+
71
+ rowspanを抽出し、rowspanが1を超える場合には
72
+
73
+ rowspanの数だけ`.find_next_siblings()`を取得し
74
+
75
+ 先頭列に[機械種別]の記載がないデータの数(列×2行)文のデータをスライスして抽出しています。
76
+
77
+ 抽出したデータの先頭に保持していたgenre変数(機械種別名)をおいてデータを整形し
78
+
79
+ 都度resultリストに追加していき、最後にdfに変換するという流れです。
80
+
81
+
82
+
83
+ ```python
84
+
85
+ from bs4 import BeautifulSoup
86
+
87
+ import requests
88
+
89
+ import pandas as pd
90
+
91
+
92
+
93
+ url = 'https://ja.nc-net.or.jp/search/equipment/?cl[]=1'
94
+
95
+
96
+
97
+ res = requests.get(url)
98
+
99
+ soup = BeautifulSoup(res.content, 'html.parser')
100
+
101
+ tables = soup.find('table', id='equip1_list')
102
+
103
+
104
+
105
+ #print(tables.prettify())
106
+
107
+ header = [th.text for th in tables.find_all('th')]
108
+
109
+ result = []
110
+
111
+ for e, tr in enumerate(tables.find('tbody').find_all('tr')):
112
+
113
+ if e != 0:
114
+
115
+ genre, maker, num = [td.text for td in tr.find_all('td')]
116
+
117
+ span = int(tr.find_all('td')[0].get('rowspan'))
118
+
119
+ result.append([genre, maker, num.replace('台', '')])
120
+
121
+
122
+
123
+ if span > 1:
124
+
125
+ after = [td.text for td in tr.find_next_siblings()[0: (span-1)*2]]
126
+
127
+ for i in range(0, len(after), 2):
128
+
129
+ maker, num = after[i: i+2]
130
+
131
+ result.append([genre, maker, num.replace('台', '')])
132
+
133
+
134
+
135
+
136
+
137
+ df = pd.DataFrame(result)
138
+
139
+ df.to_csv('result.csv', encoding='cp932', header=header, index=False)
140
+
141
+ ```