2013-04-28 77 views
0

我一直在写坏的Perl一段时间,但我试图学习编写坏python。我已经阅读了几天我遇到的问题(并且因此了解了有关unicode的更多信息),但我仍然在下面的代码中遇到了流氓em-dash的问题:Python刮板的Unicode问题

import urllib2 

def scrape(url): 
# simplified 
    data = urllib2.urlopen(url) 
    return data.read() 

def query_graph_api(url_list): 
# query Facebook's Graph API, store data. 
    for url in url_list: 
     graph_query = graph_query_root + "%22" + url + "%22" 
     query_data = scrape(graph_query) 
     print query_data #debug console 

### START HERE #### 

graph_query_root = "https://graph.facebook.com/fql?q=SELECT%20normalized_url,share_count,like_count,comment_count,total_count%20FROM%20link_stat%20WHERE%20url=" 

url_list = ['http://www.supersavvyme.co.uk', 'http://www.supersavvyme.co.uk/article/how-to-be-happy–laugh-more'] 

query_graph_api(url_list) 

(这是刮的更简化表示,BTW原来采用的是网站的sitemap.xml打造的URL列表,然后查询Facebook的图形API对每一个信息 - 这里的the original scraper

我试图去调试这个主要是试图模仿重写莎士比亚的无限猴子。我通常的方法(搜索用于错误消息的StackOverflow,复制并粘贴解决方案)失败。

问题:如何对数据进行编码,以便像第二个URL中的em-dash这样的扩展字符不会破坏我的代码,但仍然可以在FQL查询中工作?

P.S.我甚至不知道我是否问正确的问题:可能urllib.urlencode帮我在这里(当然,这将使该graph_query_root更容易和漂亮创建...

--- 8 < ----

我从ScraperWiki实际刮刀获得回溯如下:

http://www.supersavvyme.co.uk/article/how-to-be-happy–laugh-more 
Line 80 - query_graph_api(urls) 
Line 53 - query_data = scrape(graph_query) -- query_graph_api((urls=['http://www.supersavvyme.co.uk', 'http://...more 
Line 21 - data = urllib2.urlopen(unicode(url)) -- scrape((url=u'https://graph.facebook.com/fql?q=SELECT%20url,...more 
/usr/lib/python2.7/urllib2.py:126 -- urlopen((url=u'https://graph.facebook.com/fql?q=SELECT%20url,no...more 
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 177: ordinal not in range(128) 
+1

你能否在你的问题中包含精确的问题? – 2013-04-28 18:57:14

+0

你可以发布回溯? – MikeHunter 2013-04-28 19:04:26

回答

1

如果您正在使用Python 3.x中,所有你需要做的就是添加一行,并换另:

gq = graph_query.encode('utf-8') 
query_data = scrape(gq) 

如果您正在使用Python 2.x中,首先把下面一行在模块文件的顶部:

# -*- coding: utf-8 -*-(读什么这是here

,然后让你的所有字符串文字unicode和编码只是传递到之前的urlopen:

def scrape(url): 
# simplified 
    data = urllib2.urlopen(url) 
    return data.read() 

def query_graph_api(url_list): 
# query Facebook's Graph API, store data. 
    for url in url_list: 
     graph_query = graph_query_root + u"%22" + url + u"%22" 
     gq = graph_query.encode('utf-8') 
     query_data = scrape(gq) 
     print query_data #debug console 

### START HERE #### 

graph_query_root = u"https://graph.facebook.com/fql?q=SELECT%20normalized_url,share_count,like_count,comment_count,total_count%20FROM%20link_stat%20WHERE%20url=" 

url_list = [u'http://www.supersavvyme.co.uk', u'http://www.supersavvyme.co.uk/article/how-to-be-happy–laugh-more'] 

query_graph_api(url_list) 

像你使用3.x中,这是对付像这样的东西,真是再好不过了它从代码看起来。但是你必须在必要时进行编码。在2.x中,最好的建议是做默认的3.x:在整个代码中使用unicode,并且只在调用字节时进行编码。