Skip to content

Instantly share code, notes, and snippets.

Last active October 7, 2017 13:09
Show Gist options
  • Save kurozumi/7ef2ef722e4520fba09c9f4d83ecc453 to your computer and use it in GitHub Desktop.
Save kurozumi/7ef2ef722e4520fba09c9f4d83ecc453 to your computer and use it in GitHub Desktop.
【Python】Python3でYahoo Shopping APIを使って商品検索をする方法
# coding: utf-8
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
class Yahoo(object):
response = None
def __init__(self, appid=None):
self.params = {
"appid": appid
# APIを叩く
def request(self, url, **kwargs):
query_string = urllib.parse.urlencode(self.params)
if query_string:
url = url + query_string
with urllib.request.urlopen(url) as f:
self.response =
self.request_url = f.geturl()
return self
# 生のレスポンスデータ
def raw(self):
return self.response
# XMLをパースしたデータ
def parse(self):
if self.response is None:
return ET.fromstring(self.response)
def total(self):
return self.parse.attrib["totalResultsAvailable"]
def hits(self):
return int(self.parse.attrib["totalResultsReturned"])
def first(self):
return int(self.parse.attrib["firstResultPosition"])
def page(self):
return self.first + self.hits - 1
class Shopping(Yahoo):
NS = {
"itemSearch": "urn:yahoo:jp:itemSearch",
"itemLookup": "urn:yahoo:jp:itemLookup"
def lookup(self, **kwargs):
self.prefix = "itemLookup"
url = ""
return self.request(url, **kwargs)
def search(self, **kwargs):
self.prefix = "itemSearch"
url = ""
return self.request(url, **kwargs)
# 商品情報を取得するジェネレータ
def items(self):
match = "{}:Hit".format(self.prefix)
for item in self.parse[0].findall(match, self.NS):
self._item = item
yield self
def find(self, tag):
item = self._item
for t in tag.split("."):
item = item.find("{}:{}".format(self.prefix, t), self.NS)
return item
def id(self):
return self.find("Code").text
def category(self):
return self.find("Category.Current.Name").text
def name(self):
return self.find("Name").text
def url(self):
return self.find("Url").text
def price(self):
return self.find("Price").text
def fixedprice(self):
return self.find("PriceLabel.FixedPrice").text
def shopname(self):
return self.find("Store.Name").text
def jancode(self):
return self.find("JanCode").text
if __name__ == "__main__":
# APPIDを取得して下さい。
shopping = Shopping(APPID)
response =**{"query": "Python"})
for item in response.items:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment