我一直在写坏的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)
你能否在你的问题中包含精确的问题? – 2013-04-28 18:57:14
你可以发布回溯? – MikeHunter 2013-04-28 19:04:26