将由多个变量生成的Python URL分解回组件

2024-10-01 00:23:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我声明了一个变量:

url = baseUrl + urlParam(pair[1].value, conditionMapping[pair[0].value])

其中:

baseUrl = 'http://www.ebay.com/sch/i.html?'
conditionMapping = {'New': '1000', 'New Other': '1000', 'Used': '12'}

def urlParam(product, condition):
    return urlencode({'_from':'R40',
                       '_sacat':'0',
                       '_nkw':product,
                       'LH_Complete':'1',
                       'LH_Sold':'1',
                       'rt':'nc',
                      '_sop':'3',
                      'LH_BIN':'1',
                      'LH_ItemCondition' : condition})

pair[0]pair[1]是使用openpyxl从电子表格的单元格中获取的值。你知道吗

这将导致程序生成如下URL:

http://www.ebay.com/sch/i.html?rt=nc&LH_Complete=1&_nkw=Columbia+Hiking+Pants&LH_Sold=1&_sacat=0&LH_BIN=1&_from=R40&_sop=3&LH_ItemCondition=1000

我现在想做的是,每当对其中一个URL的请求失败时,我都希望能够对URL进行“反向工程”,以找出该URL的对[0]和对[1](产品条件和产品名称)的值。已知url变量是如何构造的,是否可以这样做?Alternativley,有没有更好的方法来设置我的变量(和/或其他输入)来促进这一点?你知道吗


Tags: comhttpurlnewvaluehtmlwwwebay
2条回答
>>> urlparse.parse_qs(urlparse.urlparse('''http://www.ebay.com/sch/i.html?rt=nc&LH_Complete=1&_nkw=Columbia+Hiking+Pants&LH_Sold=1&_sacat=0&LH_BIN=1&_from=R40&_sop=3&LH_ItemCondition=1000''').query)
{'rt': ['nc'], 'LH_Complete': ['1'], '_nkw': ['Columbia Hiking Pants'], 'LH_Sold': ['1'], '_sacat': ['0'], 'LH_BIN': ['1'], '_from': ['R40'], '_sop': ['3'], 'LH_ItemCondition': ['1000']}

您可以在处理URL的函数中进行URL处理,如果失败,可以使用try/catch块返回这些值。例如:

def doStuffWithURL(firstParam,secondParam):
    url = baseUrl + urlParam(firstParam, conditionMapping[secondParam])
    try:
        #whatever you were doing
        response = requests.get(url)
    except Exception, e:
        print e

或者(首选方法)捕获特定的异常,并让其他人引发错误:

    except requests.exceptions.HTTPError, e:
         print e

相关问题 更多 >