回答編集履歴

3

コード修正

2017/08/09 10:09

投稿

can110
can110

スコア38266

test CHANGED
@@ -8,24 +8,62 @@
8
8
 
9
9
  これらは`BeautifulSoup`では単なるテキストとして扱われるため、取り除かれません。
10
10
 
11
- ちょっと無理やりですが、以下のように正規表現本文のみ抽出できました。
11
+ ちょっと無理やりですが、`description`部分を`HTML`とみなして解析することで抽出できました。
12
12
 
13
13
 
14
14
 
15
+ 検証コード
16
+
15
17
  ```Python
18
+
19
+ import requests
20
+
21
+ from bs4 import BeautifulSoup
22
+
23
+ import re
24
+
25
+
26
+
27
+ url = 'http://feeds.reuters.com/reuters/JPBusinessNews'
28
+
29
+ #url = 'http://feeds.reuters.com/reuters/healthNews'
30
+
31
+ html = requests.get(url)
32
+
33
+ root = BeautifulSoup(html.content, 'html.parser')
34
+
35
+
16
36
 
17
37
  for link in root.findAll("item"):
18
38
 
19
39
  print(link.find("title").text)
20
40
 
41
+ print('-----')
42
+
21
- desc = link.find("description").text
43
+ desc = link.find('description').text
22
44
 
23
45
  #print(desc)
24
46
 
25
- # 「本文~<div(など表示用の要素)~</a>」→「本文~」を抽出
47
+
26
48
 
49
+ # 方法1:HTMLとみなして解析
50
+
51
+ desc = BeautifulSoup(desc,'html.parser')
52
+
53
+ desc = desc.text.rstrip()
54
+
55
+
56
+
57
+ # 方法2:「本文~<div(など表示用の要素)~</a>」→「本文~」を抽出
58
+
59
+ # 一部の項目で正規表現が一致しない場合あり
60
+
27
- desc = re.match(r'(.*)<div',desc).group(1)
61
+ #desc = re.match(r'(.*)<div',desc).group(1)
62
+
63
+
28
64
 
29
65
  print(desc)
30
66
 
67
+ print('-----')
68
+
31
69
  ```

2

コード修正

2017/08/09 10:09

投稿

can110
can110

スコア38266

test CHANGED
@@ -1,13 +1,31 @@
1
1
  `BeautifulSoup`を使っていれば`.text`または[.get_text()](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text)でテキストのみ抽出できます。
2
+
3
+
4
+
5
+ #### 元データを確認したうえで修正
6
+
7
+ 元データ`RSS(XML)`を確認したところ`description`要素内には、本文に加え、`<div~</a>`のような表示用の要素?が**テキスト**として含まれていました。
8
+
9
+ これらは`BeautifulSoup`では単なるテキストとして扱われるため、取り除かれません。
10
+
11
+ ちょっと無理やりですが、以下のように正規表現で本文のみ抽出できました。
2
12
 
3
13
 
4
14
 
5
15
  ```Python
6
16
 
7
- for link in htmlSource.findAll("item"):
17
+ for link in root.findAll("item"):
8
18
 
9
19
  print(link.find("title").text)
10
20
 
11
- print(link.find("description").text)
21
+ desc = link.find("description").text
22
+
23
+ #print(desc)
24
+
25
+ # 「本文~<div(など表示用の要素)~</a>」→「本文~」を抽出
26
+
27
+ desc = re.match(r'(.*)<div',desc).group(1)
28
+
29
+ print(desc)
12
30
 
13
31
  ```

1

リンク追加

2017/08/09 09:42

投稿

can110
can110

スコア38266

test CHANGED
@@ -1,4 +1,6 @@
1
- `BeautifulSoup`を使っていれば`.text`または`.get_text()`でテキストのみ抽出できます。
1
+ `BeautifulSoup`を使っていれば`.text`または[.get_text()](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text)でテキストのみ抽出できます。
2
+
3
+
2
4
 
3
5
  ```Python
4
6