这是一个脚本,它以Amazon作为输入,从URL中提取ASIN/ISBN,并使用undefined获取详细信息。
对于这个任务,我查看了许多Amazon并观察了以下内容:
我希望我涵盖了所有的事情,但是如果我漏掉了什么案子,请告诉我。
其次,我只关心亚马逊印度。因此,如果我给出亚马逊美国或任何其他国家的ASIN,或者给出定价信息为零,则ASIN是无效的。我不知道为什么会导致这样的行为(示例)。
流程:获取URL,检查ASIN或ISBN,如果没有返回false,请使用API获取名称、价格、URL和产品图像。
import re
from amazon.api import AmazonAPI
AMAZON_ACCESS_KEY = 'AKI...JP2'
AMAZON_SECRET_KEY = 'Eto...uxV'
AMAZON_ASSOC_TAG = 'p...1'
asin_regex = r'/([A-Z0-9]{10})'
isbn_regex = r'/([0-9]{10})'
def get_amazon_item_id(url):
# return either ASIN or ISBN
asin_search = re.search(asin_regex, url)
isbn_search = re.search(isbn_regex, url)
if asin_search:
return asin_search.group(1)
elif isbn_search:
return isbn_search.group(1)
else:
# log this URL
return None
def get_amazon_product_meta(url):
# the input URL is always of amazon
amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG, region="IN")
item_id = get_amazon_item_id(url)
if not item_id:
return None
try:
product = amazon.lookup(ItemId=item_id)
except amazon.api.AsinNotFound:
# log this ASIN
return None
# product.price_and_currency returns in the form (price, currency)
product_price = product.price_and_currency[0]
if product_price:
return product.offer_url, product.title, product.large_image_url, product_price
return None发布于 2014-07-09 13:21:21
这应该是一个简短的回顾,主要是因为您的代码看起来相当不错。
我对Amazon没有任何经验,但据我所知,您正在使用它,正如我所期望的那样。
我只想谈一谈,并能挑出以下几点:
asin_regex和isbn_regex略有误导。在Python中,正则表达式模式和正则表达式对象是有区别的。后缀_regex本身意味着变量可以识别表达式,而表达式又意味着变量是正则表达式对象。因为您的变量本身无法识别表达式,所以我将使用后缀_pattern。get_amazon_id中的逻辑是完全正确的。这是我个人的偏好,在这种情况下,您只是在if块内返回,只需使用if语句,不使用elif或else块: if asin_search:返回asin_search.group(1)如果isbn_search:返回isbn_search.group(1),则不返回任何一个,这完全是个人偏好,只需获得另一个版本即可。但是,我建议做的是使用for循环来减少一些次要的代码重复,并使代码更加灵活:对于asin_search中的搜索,isbn_search: if搜索:返回search.group(1),如果出于某种原因,如果出现另一个ID类型,那么上面的代码将是最好的。因此,不必添加另一个if语句,只需将new_id_search添加到for循环list中即可。\w和\d字符: asin_regex = r'/(\w{10})‘isbn_regex = r'/(\d{10})’\d字符只会使您当前的短正则表达式更短,而\w字符则有助于防止由于某种未知原因ASIN或ISBN包含小写字符的情况。https://codereview.stackexchange.com/questions/56554
复制相似问题