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

質問編集履歴

1

大幅な概要修正

2018/06/06 05:22

投稿

rina0366
rina0366

スコア58

title CHANGED
@@ -1,1 +1,1 @@
1
- Pythonによるインデントエラーの解消について
1
+ Pythonによるエラーの解消について
body CHANGED
@@ -2,22 +2,22 @@
2
2
 
3
3
  Pythonによるスクレイピング機能の実装を行っております。
4
4
  概要と致しまして、url.txtから該当のurlから必要な情報を読み込み、csvへ書き出す作業になります。
5
- しかし、インデントエラーにより実行ができません。
5
+ しかし、エラーにより実行ができません。
6
6
 
7
7
  ### 試したこと
8
+ (修正により)
8
9
 
10
+ 大幅に記載する理由を変更致します。
9
- 現状のエラーではインデント以外のエラー表記ておりますが、先ほインデント調整行っているときはインデントのみのときもありました、しかし、全体の構成を考えたときのインデントの配置を意識して現在のコードに至る所存であります、やはり何度調整してもインデントのエラーになってしいます
11
+ インデックスエラーによる表記はなくなったのですが関数やtryなどの記載ましたが構文エラーにより実行が行えくなりした
10
12
 
11
- 現状の知識でどのような修正により、改善できるか不明であり、教授して頂けないでしょうか。
12
13
 
13
-
14
14
  ### 発生している問題・エラーメッセージ
15
15
 
16
16
  ```
17
- File "surugaya.py", line 35
17
+ File "surugaya.py", line 14
18
- except:
18
+ for line in lines2:
19
- ^
19
+ ^
20
- IndentationError: unexpected indent
20
+ SyntaxError: invalid syntax
21
21
  ```
22
22
 
23
23
  ### 該当のソースコード
@@ -27,36 +27,37 @@
27
27
  import urllib.request as req
28
28
  import csv
29
29
 
30
+ def startScrapy():
31
+ try:
30
- f = open('url.txt')
32
+ f = open('url.txt')
31
- lines2 = f.readlines()
33
+ lines2 = f.readlines()
32
- f.close()
34
+ f.close()
35
+ pa = []
33
36
 
34
37
 
35
- pa = []
38
+ # 取得
39
+ for line in lines2:
40
+ url = "https://www.suruga-ya.jp/product/detail/" + line
41
+ res = req.urlopen(url)
42
+ soup = BeautifulSoup(res, 'html.parser')
36
43
 
37
- # 取得
38
- for line in lines2:
39
- url = "https://www.suruga-ya.jp/product/detail/" + line
40
- res = req.urlopen(url)
41
- soup = BeautifulSoup(res, 'html.parser')
42
-
43
- title1 = soup.select('#item_title')
44
+ title1 = soup.select('#item_title')
44
- if len(title1) > 0 :
45
+ if len(title1) > 0 :
45
- for i in title1:
46
+ for i in title1:
46
- pt = i.get_text().replace('\n', '')
47
+ pt = i.get_text().replace('\n', '')
47
- else:
48
+ else:
48
- pt = 'Nothing Product Name'
49
+ pt = 'Nothing Product Name'
49
50
 
50
- p_list = soup.select('#price')
51
+ p_list = soup.select('#price')
51
- if len(p_list) > 0 :
52
+ if len(p_list) > 0 :
52
- for x in p_list:
53
+ for x in p_list:
53
- pl = x.get_text().replace('\n', '').replace('\r', '')
54
+ pl = x.get_text().replace('\n', '').replace('\r', '')
54
- else:
55
+ else:
55
- pl = 'Nothing Product Price'
56
+ pl = 'Nothing Product Price'
56
- pa += [line, pt, pl, 0]
57
+ pa += [line, pt, pl, 0]
57
- print(pa)
58
+ print(pa)
58
59
 
59
- return pa
60
+ return pa
60
61
  except:
61
62
  print("失敗")
62
63
 
@@ -65,4 +66,7 @@
65
66
  with open('price.csv', 'w', encoding='utf-8') as _file:
66
67
  writer = csv.writer(_file, lineterminator='\n')
67
68
  writer.writerow(pa)
69
+
70
+
71
+
68
72
  ```