python - 分割字符串时丢失编码

标签 python google-app-engine encoding utf-8 urlfetch

[已编辑]

我正在使用 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() 方法,但效果不佳。

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

最佳答案

我是一名 java 开发人员,我使用 jsoup 进行 HTML 解析。我为 python 找到了类似的。这可能会帮助您并节省您的时间。

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

健脑食品: Python regular expression for HTML parsing (BeautifulSoup)

关于python - 分割字符串时丢失编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9453621/

相关文章:

python - 在 Saxon/C 中使用条件包含/静态参数?

python - 基于特定模式和编辑字符串的拆分

python - 如果 X 中有多个 Y,Python 究竟如何解析 "from X import Y"?

python - 音频导出失败,可能是因为您指定的比特率大于两倍或对于视频编解码器而言太低

java - App Engine 启动和日志记录问题

python - 使用无效字符解码 JSON

windows-7 - 使用 SinkWriter 编码视频时更改 h.264 质量

android - 使用游标从 android 中的谷歌应用引擎查询

java - 无法将 Maven 项目转换为 App Engine 标准项目

python - 使用字符集编码 UTF-8 发送电子邮件 - Python + boto3