質問するログイン新規登録

回答編集履歴

1

追記

2020/10/28 05:52

投稿

nto
nto

スコア1438

answer CHANGED
@@ -19,4 +19,65 @@
19
19
  elements2 = soup.select("#detail > div.bg.bg-theme.border.type-detail > div > div > article > div:nth-child(5) > ul")
20
20
  commentaries = [cmt.text for cmt in elements2]
21
21
  time.sleep(1)
22
+ ```
23
+
24
+
25
+ ### 追記
26
+ 上記ではログインしている事を前提で~と回答を致しましたが
27
+ 恐らくは質問者様はスクレイピングの際にログイン処理は行っていないでしょう。
28
+ ログイン処理については恐らくはseleniumを使用した方が簡易的でしょう。
29
+ となると、各項の取得もrequestsを使用するのではなくselenium上で取得を行い
30
+ `driver.page_source`でソースを取得しBSで各要素を出力するというのがベストな方法だと思います。
31
+
32
+ ```python
33
+ from selenium import webdriver
34
+ from selenium.webdriver.chrome.options import Options
35
+ from bs4 import BeautifulSoup
36
+ import time
37
+
38
+ idpw = ('ID', 'PASSWORD')
39
+ url = 'https://input.medilink-study.com/index.php'
40
+ target = "https://input.medilink-study.com/detail.php?index={}"
41
+
42
+
43
+ options = Options()
44
+ options.add_argument('--headless') # ←コメントアウトでヘッドレスモード解除
45
+ driver = webdriver.Chrome(chrome_options=options)
46
+ driver.implicitly_wait(10)
47
+ driver.get(url)
48
+
49
+ # ログイン処理
50
+ login_button = driver.find_element_by_class_name('icon-login').click()
51
+ driver.find_element_by_class_name('cmn-form-userid').send_keys(idpw[0])
52
+ driver.find_element_by_class_name('cmn-form-password').send_keys(idpw[1])
53
+ driver.find_element_by_class_name('cmn-form-login-button').click()
54
+ time.sleep(5)
55
+
56
+
57
+ for i in range(1, 58):
58
+ driver.get(target.format(i))
59
+ html = driver.page_source
60
+ soup = BeautifulSoup(html, 'html.parser')
61
+
62
+ # お題と回答の取得
63
+ elements = soup.select('.heading')
64
+ title = elements[0].string
65
+ answer = elements[1].text
66
+
67
+ # 解説の取得
68
+ elements2 = soup.select("#detail > div.bg.bg-theme.border.type-detail > div > div > article > div:nth-child(5) > ul > li")
69
+ commentaries = {}
70
+ if len(elements2) != 0:
71
+ for cmt in elements2:
72
+ key, value = cmt.select('div')
73
+ key, value = key.text, value.text
74
+ commentaries[key] = value
75
+ # 解説要素がなかった場合
76
+ else:
77
+ commentaries = 'comment was none'
78
+
79
+ print(title, answer)
80
+ print(commentaries)
81
+ print('='*50)
82
+ time.sleep(1)
22
83
  ```