[已编辑]
我正在使用 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/