非常感谢您的回答,约翰和史蒂文。你的回答让我有了不同的想法,这让我找到了问题的根源,也找到了一个可行的解决方案。
我正在使用以下测试代码:
import urllib
import urllib2
from scrapy.selector import HtmlXPathSelector
from scrapy.http import HtmlResponse
URL = "http://jackjones.bestsellershop.com/DE/jeans/clark-vintage-jos-217-sup/37246/37256"
url_handler = urllib2.build_opener()
urllib2.install_opener(url_handler)
handle = url_handler.open(URL)
response = handle.read()
handle.close()
html_response = HtmlResponse(URL).replace(body=response) # Problematic line
hxs = HtmlXPathSelector(html_response)
desc = hxs.select('//span[@id="attribute-content"]/text()')
desc_text = desc.extract()[0]
print desc_text
print desc_text.encode('utf-8')
在 Scrapy shell 中,当我提取描述数据时,结果很好。这让我有理由怀疑我的代码有问题,因为在pdb
提示符下,我在提取的数据中看到了替换字符。
我浏览了Response 类的 Scrapy 文档,并将上面的代码调整为:
import urllib
import urllib2
from scrapy.selector import HtmlXPathSelector
from scrapy.http import HtmlResponse
URL = "http://jackjones.bestsellershop.com/DE/jeans/clark-vintage-jos-217-sup/37246/37256"
url_handler = urllib2.build_opener()
urllib2.install_opener(url_handler)
handle = url_handler.open(URL)
response = handle.read()
handle.close()
#html_response = HtmlResponse(URL).replace(body=response)
html_response = HtmlResponse(URL, body=response)
hxs = HtmlXPathSelector(html_response)
desc = hxs.select('//span[@id="attribute-content"]/text()')
desc_text = desc.extract()[0]
print desc_text
print desc_text.encode('utf-8')
我所做的更改是将行替换html_response = HtmlResponse(URL).replace(body=response)
为html_response = HtmlResponse(URL, body=response)
. 据我了解,该replace()
方法从编码的角度以某种方式破坏了特殊字符。
如果有人想详细说明该方法到底出了什么replace()
问题,我将非常感谢您的努力。
再一次感谢你。