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

質問編集履歴

3

追加質問の自己解決

2017/04/08 21:34

投稿

chrokurojp
chrokurojp

スコア26

title CHANGED
File without changes
body CHANGED
@@ -30,6 +30,10 @@
30
30
 
31
31
  アドバイスお願いします
32
32
 
33
+
34
+ 「f = open("./static/"+os.path.basename(resource), "wb")」
35
+ にする事で解決できました
36
+
33
37
  # web_crawler.py
34
38
 
35
39
  ```

2

パス修正

2017/04/08 21:34

投稿

chrokurojp
chrokurojp

スコア26

title CHANGED
File without changes
body CHANGED
@@ -30,8 +30,12 @@
30
30
 
31
31
  アドバイスお願いします
32
32
 
33
+ # web_crawler.py
34
+
35
+ ```
33
- # python3 web_crawler.py "https://search.yahoo.co.jp/image/search?ei=UTF-8&fr=sfp_as&aq=-1&oq=&ts=1609&p=%E8%B5%B0%E3%82%8C%EF%BC%81
36
+ python3 web_crawler.py "https://search.yahoo.co.jp/image/search?ei=UTF-8&fr=sfp_as&aq=-1&oq=&ts=1609&p=%E8%B5%B0%E3%82%8C%EF%BC%81
34
37
  %E3%80%80%E3%82%B3%E3%83%BC%E3%83%89%E5%AD%A6%E5%9C%92&meta=vc%3D" .jpeg,.jpg
38
+ ```
35
39
 
36
40
  ```
37
41
  #-*- coding:utf-8 -*-

1

追加質問の為

2017/04/08 21:05

投稿

chrokurojp
chrokurojp

スコア26

title CHANGED
File without changes
body CHANGED
@@ -17,4 +17,164 @@
17
17
  Python 3.6.1
18
18
 
19
19
  pip3 freeze | grep beautifulsoup
20
- beautifulsoup4==4.5.3
20
+ beautifulsoup4==4.5.3
21
+
22
+
23
+ 【追加質問です。】
24
+ 上記は解決しました。
25
+
26
+ 下記を実行するとプログラムが置かれたフォルダ直下に保存される為、
27
+ f = open(os.path.basename("./static/"+resource), "wb")
28
+ と書き換えれば指定ディレクトリに保存できる考えたのですが
29
+ うまく行きませんでした。
30
+
31
+ アドバイスお願いします
32
+
33
+ # python3 web_crawler.py "https://search.yahoo.co.jp/image/search?ei=UTF-8&fr=sfp_as&aq=-1&oq=&ts=1609&p=%E8%B5%B0%E3%82%8C%EF%BC%81
34
+ %E3%80%80%E3%82%B3%E3%83%BC%E3%83%89%E5%AD%A6%E5%9C%92&meta=vc%3D" .jpeg,.jpg
35
+
36
+ ```
37
+ #-*- coding:utf-8 -*-
38
+
39
+ import os
40
+ import sys
41
+ import time
42
+ import bs4
43
+ import urllib.request
44
+
45
+ def crawring(url, extensions):
46
+ """
47
+ Content:
48
+ クローリング
49
+ Param:
50
+ url: クローリングするURL
51
+ extensions: 取得するリソースの拡張子(list)
52
+ """
53
+ # 指定したURLのHTMLを取得
54
+ html = get_html_string(url)
55
+ if len(html) < 1:
56
+ print("HTMLが取得できませんでした。")
57
+ print("URLを確認してください。")
58
+ sys.exit(1)
59
+
60
+ # リソース取得
61
+ get_resource(html, extensions)
62
+
63
+ def get_resource(html, extensions):
64
+ """
65
+ Content:
66
+ リソース取得
67
+ Param
68
+ html: HTML
69
+ extensions 拡張子のリスト
70
+ """
71
+
72
+ resource_list = []
73
+
74
+ soup = bs4.BeautifulSoup(html,'lxml')
75
+ for a_tag in soup.find_all("a"):
76
+ href_str = a_tag.get("href")
77
+ try:
78
+ (path, ext) = os.path.splitext(href_str)
79
+ if ext in extensions:
80
+ resource_list.append(href_str)
81
+ except:
82
+ pass
83
+
84
+ resource_list = sorted(set(resource_list), key=resource_list.index)
85
+ for resource in resource_list:
86
+ try:
87
+ print("download ---> [%s]" % os.path.basename(resource))
88
+ request = urllib.request.urlopen(resource)
89
+ f = open(os.path.basename("./static/"+resource), "wb")
90
+ f.write(request.read())
91
+ except Exception as e:
92
+ print(e)
93
+ print("download failed ... [%s]" % os.path.basename(resource))
94
+ finally:
95
+ time.sleep(3)
96
+
97
+ def get_html_string(url):
98
+ """
99
+ Content:
100
+ HTML取得
101
+ Param:
102
+ url HTMLを取得するURL
103
+ """
104
+ decoded_html = ""
105
+
106
+ # HTMLを取得
107
+ try:
108
+ request = urllib.request.urlopen(url)
109
+ html = request.read()
110
+ except:
111
+ return decoded_html
112
+
113
+ # エンコードを取得
114
+ enc = check_encoding(html)
115
+ if enc == None:
116
+ return decoded_html
117
+
118
+ # HTMLをデコード
119
+ decoded_html = html.decode(enc)
120
+
121
+ return decoded_html
122
+
123
+ def check_encoding(byte_string):
124
+ """
125
+ Content:
126
+ 文字コード確認
127
+ Param:
128
+ byte_string: バイト文字列
129
+ """
130
+ encoding_list = ["utf-8", "utf_8", "euc_jp",
131
+ "euc_jis_2004", "euc_jisx0213", "shift_jis",
132
+ "shift_jis_2004","shift_jisx0213", "iso2022jp",
133
+ "iso2022_jp_1", "iso2022_jp_2", "iso2022_jp_3",
134
+ "iso2022_jp_ext","latin_1", "ascii"]
135
+
136
+ for enc in encoding_list:
137
+ try:
138
+ byte_string.decode(enc)
139
+ break
140
+ except:
141
+ enc = None
142
+
143
+ return enc
144
+
145
+
146
+ def check_args():
147
+ """
148
+ Content:
149
+ 起動引数確認
150
+ """
151
+ if len(sys.argv) == 3:
152
+ return True
153
+ else:
154
+ return False
155
+
156
+ def print_usage():
157
+ print("Usage: %s URL Extensions" % __file__)
158
+ print("URLにはクロールしたいウェブサイトのアドレスを指定してください。")
159
+ print("Extensionsにはクロールしたときに取得するファイルの拡張子を指定してください。")
160
+ print("Extensionsはカンマ区切りで複数指定できます。")
161
+
162
+ def main():
163
+ """
164
+ Content:
165
+ main
166
+ """
167
+ # 引数確認
168
+ if check_args() is False:
169
+ print_usage()
170
+ sys.exit(1)
171
+
172
+ url = sys.argv[1]
173
+ extensions = sys.argv[2].split(",")
174
+
175
+ # クロール開始
176
+ crawring(url, extensions)
177
+
178
+ if __name__ == "__main__":
179
+ main()
180
+ ```