Unicode issue with Python scraper



我写不好的perl已经有一段时间了,但我正试图学习写不好的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)

(顺便说一句,这是一个非常简化的scraper表示。原始版本使用站点的sitemap.xml来构建url列表,然后查询Facebook的Graph API以获取每个url的信息(这是原始的scraper)

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

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

注:我甚至想知道我是否在问正确的问题:urllib.urlencode可能会帮助我在这里(当然它会使graph_query_root更容易和更漂亮的创建…

8 & lt;

,

我从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)

如果您正在使用Python 3。X,您所要做的就是添加一行并更改另一行:

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

如果你正在使用Python 2。X,首先在模块文件的顶部放入以下行:

# -*- coding: utf-8 -*-

,然后在传递给urlopen之前将所有的字符串字面值unicode和编码:

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,最好的建议是做什么?默认情况下,X在整个代码中使用unicode,并且仅在调用字节时进行编码。