【问题标题】:TypeError byte indices must be integers or slices, not strTypeError 字节索引必须是整数或切片,而不是 str
【发布时间】:2022-01-09 07:26:37
【问题描述】:

关于我的代码收到的 TypeError 的问题。

代码的开始:

domain = "https://bdgastore.com"
handle = 'xt-4-advanced-8'
url = domain + "/products/" + handle + ".json"

##
# Product information
##
shoeSize = "11"
quantity = "1"

options = webdriver.ChromeOptions()
options.add_argument("--incognito")
options.add_argument("--disable-extensions")
options.add_argument("--disable-gpu")
options.add_argument("--headless") # Comment that line to see script running in Chrome.
driver = webdriver.Chrome(ChromeDriverManager().install())

response = urllib.request.urlopen(url)
data = response.read()

#information
first_name='Name';
family_name='Last Name';
email='youremail@gmail.com';
address='12345 Some Street';
country='AU';
city='Mermaid Beach';
postcode='4218';
state='QLD';
mobile='0421667754';
CCNumber="1"
CCName="Test"
CCExpiry="11/25"
CCVerification="123"

#Checkout process
checkoutDetails = 'checkout[shipping_address][first_name]='+ first_name +'&checkout[shipping_address][last_name]='+ family_name +'&checkout[email]='+ email +'&checkout[shipping_address][address1]='+ address +'&checkout[shipping_address][city]='+ city +'&checkout[shipping_address][zip]='+ postcode +'&checkout[shipping_address][country_code]='+ country +'&&checkout[shipping_address][province_code]='+ state +'&checkout[shipping_address][phone]='+ mobile;

代码如下:

for variants in data['product']['variants']: 
if ((variants['inventory_quantity'] > 0) and (variants['title'] == shoeSize)):
    link = domain + '/cart/'+ str(variants['id']) +':'+ quantity +'?'+ checkoutDetails;
    driver.get(link)

而我收到的错误是

TypeError: byte indices must be integers or slices, not str

提前非常感谢您,抱歉,我还是新手。

【问题讨论】:

  • 不要用str 索引bytes 对象。
  • 能否提供datavariants的数据,一点点。
  • data 最有可能是byte 类型。

标签: python string


【解决方案1】:

这是文档中给出的example,可以看到read返回的是byte类型的数据。

从您提供的代码中可以看出,您可能期望它是dict类型,然后您可以通过json.loads方法对其进行解析。

import json

print(json.loads(b'{"a": 1}'))
# {'a': 1}

修改代码

import json
...

for variants in json.loads(data)['product']['variants']: 
if ((variants['inventory_quantity'] > 0) and (variants['title'] == shoeSize)):
    link = domain + '/cart/'+ str(variants['id']) +':'+ quantity +'?'+ checkoutDetails;
    driver.get(link)

【讨论】:

    【解决方案2】:
    variants['title'] # <-- this should be an index
    

    类似:

    variants[1]
    

    【讨论】:

      【解决方案3】:

      您需要在使用响应之前对其进行解码。试试:

      data = response.read().decode(response.headers.get_content_charset())
      

      【讨论】:

        猜你喜欢
        • 2019-02-05
        • 1970-01-01
        • 2016-02-19
        • 2015-12-09
        • 2021-11-28
        • 2017-03-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多