回答編集履歴

1

動作不良を改善

2023/11/10 07:20

投稿

melian
melian

スコア20673

test CHANGED
@@ -2,10 +2,9 @@
2
2
 
3
3
  ```python
4
4
  import pandas as pd
5
- import re
6
5
  import requests
7
6
  import wsgiref.simple_server
8
- from urllib.parse import parse_qs, quote as urlquote, urljoin
7
+ from urllib.parse import parse_qs, urljoin
9
8
  from bs4 import BeautifulSoup
10
9
 
11
10
  template = '''
@@ -19,23 +18,26 @@
19
18
  <form action="/" method="post">
20
19
  <div>
21
20
  <label for="query">検索ワード</label>
22
- <input type="text" name="query" id="query" value="@search_word@">
21
+ <input type="text" name="query" id="query" value="{search_word}">
23
22
  <button type="submit">検索</button>
24
23
  </div>
25
24
  </form>
26
25
 
27
- <!-- table -->
26
+ {result_table}
28
27
 
29
28
  </body>
30
29
  </html>
31
30
  '''
32
31
 
33
32
  def query(search_word):
34
- query_url = 'https://www.amazon.co.jp/s?k=' + urlquote(search_word)
33
+ query_url = 'https://www.amazon.co.jp/s/ref=nb_sb_noss_1'
34
+ headers = {'Referer': 'https://www.amazon.co.jp/', 'User-Agent': 'Mozilla/5.0'}
35
+ params = {'k': search_word, '__mk_ja_JP': 'カタカナ'}
36
+ res = requests.get(query_url, headers=headers, params=params)
35
- res = requests.get(query_url)
37
+ # print(res.request.url)
36
38
  soup = BeautifulSoup(res.text, 'html.parser')
39
+ df = pd.DataFrame(columns=['商品名', '価格', '送料', 'ポイント', 'URL'])
37
40
 
38
- df = pd.DataFrame(columns=['商品名', '価格', '送料', 'ポイント', 'URL'])
39
41
  items = soup.select('div[data-asin]:not([data-asin=""])')
40
42
  for item in items:
41
43
  price = item.select_one('span.a-price-whole')
@@ -51,10 +53,7 @@
51
53
  return df.to_html(escape=False)
52
54
 
53
55
  def application(env, start_response):
54
- path = env['PATH_INFO']
55
- method = env['REQUEST_METHOD']
56
+ path, method = env['PATH_INFO'], env['REQUEST_METHOD']
56
- response = ''
57
-
58
57
  if path == '/':
59
58
  if method == 'POST':
60
59
  wsgi_input = env['wsgi.input']
@@ -63,12 +62,10 @@
63
62
  data = parse_qs(form, keep_blank_values=True)
64
63
  search_word = data['query'][0]
65
64
  table = f'<hr>{query(search_word)}'
66
- response = template.replace('<!-- table -->', table)\
65
+ response = template.format(search_word=search_word, result_table=table).encode('utf-8')
67
- .replace('@search_word@', search_word)\
68
- .encode('utf-8')
69
66
  status = '200 OK'
70
67
  else:
71
- response = template.replace('@search_word@', '').encode('utf-8')
68
+ response = template.format(search_word='', result_table='').encode('utf-8')
72
69
  status = '200 OK'
73
70
  else:
74
71
  # 404 not found