В настоящее время я пишу сценарий в Python 2.7, который работает отлично, за исключением после запуска его в течение нескольких секунд, он работает в ошибку:Странно UnicodeEncodeError/AttributeError в моем сценарии
Enter Shopify website URL (without HTTP): store.highsnobiety.com
Scraping! Check log file @ z:\shopify_output.txt to see output.
!!! Also make sure to clear file every hour or so !!!
Copper Bracelet - 3mm - Polished ['3723603267']
Traceback (most recent call last):
File "shopify_sitemap_scraper.py", line 38, in <module>
print(prod, variants).encode('utf-8')
AttributeError: 'NoneType' object has no attribute 'encode'
Скрипт для получения данных с сайта Shopify, а затем распечатать его на консоли. Код здесь:
# -*- coding: utf-8 -*-
from __future__ import print_function
from lxml.html import fromstring
import requests
import time
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# Log file location, change "z://shopify_output.txt" to your location.
logFileLocation = "z:\shopify_output.txt"
log = open(logFileLocation, "w")
# URL of Shopify website from user input (for testing, just use store.highsnobiety.com during input)
url = 'http://' + raw_input("Enter Shopify website URL (without HTTP): ") + '/sitemap_products_1.xml'
print ('Scraping! Check log file @ ' + logFileLocation + ' to see output.')
print ("!!! Also make sure to clear file every hour or so !!!")
while True :
page = requests.get(url)
tree = fromstring(page.content)
# skip first url tag with no image:title
url_tags = tree.xpath("//url[position() > 1]")
data = [(e.xpath("./image/title//text()")[0],e.xpath("./loc/text()")[0]) for e in url_tags]
for prod, url in data:
# add xml extension to url
page = requests.get(url + ".xml")
tree = fromstring(page.content)
variants = tree.xpath("//variants[@type='array']//id[@type='integer']//text()")
print(prod, variants).encode('utf-8')
Самая сумасшедшая часть о том, что, когда я беру в .encode('utf-8')
это дает мне UnicodeEncodeError видели здесь:
Enter Shopify website URL (without HTTP): store.highsnobiety.com
Scraping! Check log file @ z:\shopify_output.txt to see output.
!!! Also make sure to clear file every hour or so !!!
Copper Bracelet - 3mm - Polished ['3723603267']
Copper Bracelet - 5mm - Brushed ['3726247811']
Copper Bracelet - 7mm - Polished ['3726253635']
Highsnobiety x EARLY - Leather Pouch ['14541472963', '14541473027', '14541473091']
Traceback (most recent call last):
File "shopify_sitemap_scraper.py", line 38, in <module>
print(prod, variants)
File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\xae' in position 13: character maps to <undefined>'
Любые идеи? Не знаю, что еще попробовать после нескольких часов работы в Интернете.
По-прежнему получить объект «AttributeError:« list »не имеет атрибута« encode »» с новым кодом –
@ DanielYveson извините, я не понял, что «варианты» были списком. См. Мой отредактированный ответ выше. – MattDMo
Работает красиво, спасибо. –