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

回答編集履歴

2

CSV書き込み追加

2019/01/09 06:49

投稿

barobaro
barobaro

スコア1286

answer CHANGED
@@ -2,8 +2,10 @@
2
2
  h4タグのすぐ下のpタグを検索してURLを抽出、aタグのテキストが邪魔なので削除
3
3
 
4
4
  ```python
5
+ import csv
6
+ from urllib.parse import urljoin
7
+
5
8
  import requests
6
- from urllib.parse import urljoin
7
9
  from bs4 import BeautifulSoup
8
10
 
9
11
  url = 'https://www.birdfan.net/gallery/library/sanya_mijika.html'
@@ -19,27 +21,33 @@
19
21
 
20
22
  soup = BeautifulSoup(r.content, 'html5lib')
21
23
 
22
- for i in soup.find_all('h4'):
24
+ with open('result.csv', 'w') as fw:
25
+ writer = csv.writer(fw, dialect='excel', lineterminator='\n')
23
26
 
24
- # h4より上を検索
25
- h2 = i.find_previous_sibling('h2').get_text(strip=True)
27
+ for i in soup.select('h4'):
26
- h3 = i.find_previous_sibling('h3').get_text(strip=True)
27
28
 
29
+ # h4より上を検索
28
- h4 = i.get_text(strip=True)
30
+ h2 = i.find_previous_sibling('h2').get_text(strip=True)
31
+ h3 = i.find_previous_sibling('h3').get_text(strip=True)
29
32
 
30
- # h4より下を検索
31
- p = i.find_next_sibling('p')
33
+ h4 = i.get_text(strip=True)
32
- link = urljoin(url, p.a.get('href'))
33
34
 
34
- # pのaタグ削除
35
+ # h4より下を検索
35
- p.a.decompose()
36
+ p = i.find_next_sibling('p')
37
+ link = urljoin(url, p.a.get('href'))
36
38
 
39
+ # pのaタグ削除
40
+ p.a.decompose()
41
+
37
- print(h2)
42
+ print(h2)
38
- print(h3)
43
+ print(h3)
39
- print(h4)
44
+ print(h4)
40
- print(p.text.strip())
45
+ print(p.text.strip())
41
- print(link)
46
+ print(link)
42
- print('-' * 20)
47
+ print('-' * 20)
48
+
49
+ # CSV保存
50
+ writer.writerow([h2, h3, h4, p.text.strip(), link])
43
51
  ```
44
52
  結果
45
53
  ```

1

説明追加

2019/01/09 06:49

投稿

barobaro
barobaro

スコア1286

answer CHANGED
@@ -1,3 +1,6 @@
1
+ まずh4タグを探してh4タグから上にh2タグ、h3タグを検索
2
+ h4タグのすぐ下のpタグを検索してURLを抽出、aタグのテキストが邪魔なので削除
3
+
1
4
  ```python
2
5
  import requests
3
6
  from urllib.parse import urljoin
@@ -16,7 +19,7 @@
16
19
 
17
20
  soup = BeautifulSoup(r.content, 'html5lib')
18
21
 
19
- for i in soup.select('h4'):
22
+ for i in soup.find_all('h4'):
20
23
 
21
24
  # h4より上を検索
22
25
  h2 = i.find_previous_sibling('h2').get_text(strip=True)
@@ -37,4 +40,31 @@
37
40
  print(p.text.strip())
38
41
  print(link)
39
42
  print('-' * 20)
43
+ ```
44
+ 結果
45
+ ```
46
+ フォトギャラリー野鳥図鑑(身近な鳥)
47
+ 身近な鳥(スズメ大)
48
+ スズメ
49
+ スズメ目ハタオリドリ科
50
+ 全長:14.5cm 翼開長:22.5cm
51
+ 人家付近でのみ見られる。ほおに黒い斑(幼鳥ではうすい)。
52
+ https://www.birdfan.net/pg/kind/ord17/fam1727/spe172702/
53
+ --------------------
54
+ フォトギャラリー野鳥図鑑(身近な鳥)
55
+ 身近な鳥(スズメ大)
56
+ シジュウカラ
57
+ スズメ目シジュウカラ科
58
+ 全長:14cm
59
+ 白いほお、胸から腹にネクタイ模様(太い方が雄)。
60
+ https://www.birdfan.net/pg/kind/ord17/fam1718/spe171805/
61
+ --------------------
62
+ フォトギャラリー野鳥図鑑(身近な鳥)
63
+ 身近な鳥(スズメ大)
64
+ カワラヒワ
65
+ スズメ目アトリ科
66
+ 全長:14cm
67
+ 肌色で太めのくちばし、翼と尾に黄色の斑。
68
+ https://www.birdfan.net/pg/kind/ord17/fam1724/spe172402/
69
+ --------------------
40
70
  ```