回答編集履歴

1

追記

2020/10/28 05:52

投稿

nto
nto

スコア1438

test CHANGED
@@ -41,3 +41,125 @@
41
41
  time.sleep(1)
42
42
 
43
43
  ```
44
+
45
+
46
+
47
+
48
+
49
+ ### 追記
50
+
51
+ 上記ではログインしている事を前提で~と回答を致しましたが
52
+
53
+ 恐らくは質問者様はスクレイピングの際にログイン処理は行っていないでしょう。
54
+
55
+ ログイン処理については恐らくはseleniumを使用した方が簡易的でしょう。
56
+
57
+ となると、各項の取得もrequestsを使用するのではなくselenium上で取得を行い
58
+
59
+ `driver.page_source`でソースを取得しBSで各要素を出力するというのがベストな方法だと思います。
60
+
61
+
62
+
63
+ ```python
64
+
65
+ from selenium import webdriver
66
+
67
+ from selenium.webdriver.chrome.options import Options
68
+
69
+ from bs4 import BeautifulSoup
70
+
71
+ import time
72
+
73
+
74
+
75
+ idpw = ('ID', 'PASSWORD')
76
+
77
+ url = 'https://input.medilink-study.com/index.php'
78
+
79
+ target = "https://input.medilink-study.com/detail.php?index={}"
80
+
81
+
82
+
83
+
84
+
85
+ options = Options()
86
+
87
+ options.add_argument('--headless') # ←コメントアウトでヘッドレスモード解除
88
+
89
+ driver = webdriver.Chrome(chrome_options=options)
90
+
91
+ driver.implicitly_wait(10)
92
+
93
+ driver.get(url)
94
+
95
+
96
+
97
+ # ログイン処理
98
+
99
+ login_button = driver.find_element_by_class_name('icon-login').click()
100
+
101
+ driver.find_element_by_class_name('cmn-form-userid').send_keys(idpw[0])
102
+
103
+ driver.find_element_by_class_name('cmn-form-password').send_keys(idpw[1])
104
+
105
+ driver.find_element_by_class_name('cmn-form-login-button').click()
106
+
107
+ time.sleep(5)
108
+
109
+
110
+
111
+
112
+
113
+ for i in range(1, 58):
114
+
115
+ driver.get(target.format(i))
116
+
117
+ html = driver.page_source
118
+
119
+ soup = BeautifulSoup(html, 'html.parser')
120
+
121
+
122
+
123
+ # お題と回答の取得
124
+
125
+ elements = soup.select('.heading')
126
+
127
+ title = elements[0].string
128
+
129
+ answer = elements[1].text
130
+
131
+
132
+
133
+ # 解説の取得
134
+
135
+ elements2 = soup.select("#detail > div.bg.bg-theme.border.type-detail > div > div > article > div:nth-child(5) > ul > li")
136
+
137
+ commentaries = {}
138
+
139
+ if len(elements2) != 0:
140
+
141
+ for cmt in elements2:
142
+
143
+ key, value = cmt.select('div')
144
+
145
+ key, value = key.text, value.text
146
+
147
+ commentaries[key] = value
148
+
149
+ # 解説要素がなかった場合
150
+
151
+ else:
152
+
153
+ commentaries = 'comment was none'
154
+
155
+
156
+
157
+ print(title, answer)
158
+
159
+ print(commentaries)
160
+
161
+ print('='*50)
162
+
163
+ time.sleep(1)
164
+
165
+ ```