1

[编辑]

我正在使用 Google App Engine,我正在尝试解析 HTML 内容以提取一些信息。我正在使用的代码是:

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import urlfetch
import BeautifulSoup

class MainHandler(webapp.RequestHandler):
    def get(self):
        url = 'http://ascodevida.com/ultimos'
        result = urlfetch.fetch(url=url)
        # ADVS de esta página.
        res = BeautifulSoup.BeautifulSoup(result.content).findAll('div', {'class' : 'box story'})
        ADVList = []
        for i in res:
            story = i.find('a', {'class' : 'advlink'}).string
            link = i.find('a', {'class' : 'advlink'})['href']
            ADVData = {
                'adv' : story,
                'link' : link
            }
            ADVList.append(ADVData)

        self.response.headers['Content-Type'] = 'text/html; charset=UTF-8'
        self.response.out.write(ADVList)

这段代码会产生一个带有奇怪字符的响应。我试过使用 BeautifulSoup 库的 prettify() 和 renderContent() 方法,但没有效果。

有什么解决办法吗?再次感谢。

4

2 回答 2

2

I'm a java developer and I'm using jsoup for HTML Parsing. I found similar one for python. This may help you & save your time.

http://www.crummy.com/software/BeautifulSoup/

Food for brain : Python regular expression for HTML parsing (BeautifulSoup)

于 2012-02-26T14:02:13.057 回答
0

我认为您正在直接打印列表,它调用repr,默认输出为十六进制格式(如 \xe1)。

你可以试试这个:

>>> s = u"Leer más"
>>> repr(s)
"'Leer m\\xc3\\xa1s'"

但 print 语句将尝试解码字符串:

>>> print s
Leer más

如果您想要正确的结果,只需避免列表的默认行为并自己处理每个项目。

于 2012-02-27T11:35:04.640 回答