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

質問編集履歴

3

実現したいことの修正

2021/01/30 08:44

投稿

hisa_eng
hisa_eng

スコア3

title CHANGED
File without changes
body CHANGED
@@ -1,6 +1,6 @@
1
1
  ### 前提・実現したいこと
2
2
 
3
- python3の初学者です。python3を用いて簡易的なスクレイピングのアプリを作成しています。現在は、ブラウザ上でビューファイルは問題なく表示され、urlを用いたスクレイピングも行えています。しかし、例外のurlで抽出すると、(IndexError: list index out of range)が発生するため、例外時にエラーメッセージを表示させたいのですが、表示されなくて困っております。
3
+ python3の初学者です。python3を用いて簡易的なスクレイピングのアプリを作成しています。現在は、ブラウザ上でビューファイルは問題なく表示され、urlを用いたスクレイピングも行えています。しかし、例外のurlで抽出すると、(IndexError: list index out of range)が発生するため、例外時に画面上にフォームエラーメッセージを表示させたいのですが、表示されなくて困っております。
4
4
 
5
5
  エラーメッセージの表示方法は以下のURLのサイトを参考にしました
6
6
  [参考URL](https://sleepless-se.net/2018/05/31/django%E3%81%A7form%E3%81%AE%E3%82%A8%E3%83%A9%E3%83%BC%E3%83%A1%E3%83%83%E3%82%BB%E3%83%BC%E3%82%B8%E3%82%92%E3%83%86%E3%83%B3%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88%E3%81%A7%E5%8F%96%E5%BE%97%E3%81%99/#i)

2

ディレクトリとファイル構成のGyazoを添付しました

2021/01/30 08:44

投稿

hisa_eng
hisa_eng

スコア3

title CHANGED
File without changes
body CHANGED
@@ -130,4 +130,7 @@
130
130
  Python 3.7.0
131
131
  Django 3.1.4
132
132
  requests 2.25.1
133
- beautifulsoup4 4.9.3
133
+ beautifulsoup4 4.9.3
134
+
135
+ ディレクトリとファイルの構成
136
+ https://gyazo.com/434a1275b9db6c0e147dd6c18fd1b1c1

1

view.pyのコードを追記しました

2021/01/30 08:18

投稿

hisa_eng
hisa_eng

スコア3

title CHANGED
File without changes
body CHANGED
@@ -85,7 +85,39 @@
85
85
  },
86
86
  ]
87
87
  ```
88
+ view.pyのコード
89
+ ```python
90
+ from django.shortcuts import render
91
+ from .models import News
92
+ from django.views.generic import CreateView
93
+ from django.urls import reverse_lazy
94
+ import urllib.request
95
+ import requests
96
+ from bs4 import BeautifulSoup
88
97
 
98
+
99
+ class Create(CreateView):
100
+ template_name = 'home.html'
101
+ model = News
102
+ fields = ('url',)
103
+ success_url = reverse_lazy('list')
104
+
105
+
106
+ def listfunc(request):
107
+ for post in News.objects.all():
108
+ url = post.url
109
+ list = []
110
+ response = requests.get(url)
111
+ bs = BeautifulSoup(response.text, "html.parser")
112
+ ul_tag = bs.find_all(class_="yjnSubTopics_list")
113
+ for tag in ul_tag[0]:
114
+ title = tag.a.getText()
115
+ url2 = tag.a.get("href")
116
+ list.append([title, url2])
117
+ context = {'list': list,}
118
+ return render(request, 'list.html', context)
119
+ ```
120
+
89
121
  ### 試したこと
90
122
  ①エラーメッセージを表示させる記述「{% include 'path/to/form-alert.html' %} 」の配置する場所がおかしいのでは?と考え、ファイルの先頭や別ファイルなどに移動させてみたが、特に変化なし。
91
123