Question in regards to a TypeError which I am receiving for my code.
The Beginning of the Code:
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='[email protected]';
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;
The code is the following:
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)
While else the error which I am receiving is
TypeError: byte indices must be integers or slices, not str
Thank you so much in advance and sorry, I'm still new to this.
CodePudding user response:
variants['title'] # <-- this should be an index
Something like:
variants[1]
CodePudding user response:
You need to decode the response before using it. Try:
data = response.read().decode(response.headers.get_content_charset())
CodePudding user response:
This is the example given in the document, you can see that read returns data of type byte.
As you can see from the code you provided, you are probably expecting it to be of type dict, then you can parse it through the json.loads method.
import json
print(json.loads(b'{"a": 1}'))
# {'a': 1}
Modify the code
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)
