回答編集履歴

2

f

2019/01/21 09:05

投稿

tiitoi
tiitoi

スコア21956

test CHANGED
@@ -1,4 +1,14 @@
1
1
  > ①なぜこのようなことが起こるのでしょうか
2
+
3
+
4
+
5
+ > AttributeError: ResultSet object has no attribute 'string'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?
6
+
7
+
8
+
9
+ 日本語に訳すと
10
+
11
+ > Attribute エラー: ResultSet オブジェクトは 'string' という attribute を持っていません。タグのリストをタグと勘違いして使っていませんか?find() を呼ぶべきところで find_all() を呼んでいませんか?
2
12
 
3
13
 
4
14
 

1

d

2019/01/21 09:05

投稿

tiitoi
tiitoi

スコア21956

test CHANGED
@@ -1,3 +1,7 @@
1
+ > ①なぜこのようなことが起こるのでしょうか
2
+
3
+
4
+
1
5
  `find_all()` の返り値は bs4.element.ResultSet オブジェクトです。
2
6
 
3
7
  このオブジェクトは bs4.element.Tag オブジェクトのリストと考えてよいです。
@@ -7,3 +11,45 @@
7
11
 
8
12
 
9
13
  `side_menu.find_all("a").string` とすると bs4.element.ResultSet は string という attribute は持っていないとエラーになります。
14
+
15
+
16
+
17
+ > ②もし、自分のコードのように、aタグの中身を配列として変数に代入する場合、どのように書かなければいけなかったのでしょうか
18
+
19
+
20
+
21
+ テキストのリストとして得たいのであれば、各 a タグの string 属性を要素にして、リストを作成すればよいです。
22
+
23
+
24
+
25
+ ```python
26
+
27
+ import urllib.request
28
+
29
+ from bs4 import BeautifulSoup
30
+
31
+
32
+
33
+ req = urllib.request.urlopen("https://quality-start.in/company/")
34
+
35
+ soup = BeautifulSoup(req, "html.parser")
36
+
37
+
38
+
39
+ side_menu = soup.find("div", class_="list-group")
40
+
41
+
42
+
43
+ div_texts = [a.string for a in side_menu.find_all("a")]
44
+
45
+ print(div_texts)
46
+
47
+ ```
48
+
49
+
50
+
51
+ ```
52
+
53
+ ['トップページ', '会社案内', '代表挨拶', '顧問エンジニアによるITコンサルティング', '展示会の注文管理サービス Handy', '業務システム自動生成フレームワーク MOD99', 'IT活用虎の巻', '独習Python入門サポートページ', 'お問い合わせ']
54
+
55
+ ```