将 html 页面转换为 python 中的二进制格式

Converting an html page to binary format in python

假设我有这两行:

c=urllib2.urlopen(myUrl)
html=c.read()

我对 Python 很陌生,正在寻找一种方法来将存储在 html 中的 HTML 代码转换为二进制数组,这样我就可以轻松地存储在我的 MongoDB不用担心我下载的网页的编码。

建议?

据我所知

c.read()

是一个普通的字符串(错了打我)

如果是这样,这应该对您有所帮助:
http://code.activestate.com/recipes/578291-string-to-binary/

pymongo 驱动程序已经有将字符串导入为二进制的方法。下面是这个例子:

import pymongo
import bson.binary

from pymonngo import MongoClient
from bson.binary import Binary

client = MongoClient()
db = client.test

db.btest.insert({ "bindata": Binary("Hello",0) })

db.btest.find_one()

这给你:

{u'_id': ObjectId('5582b33c268e1505371a5477'), u'bindata': Binary('Hello', 0)}

或来自 mongo shell:

> db.btest.findOne()
{
    "_id" : ObjectId("5582b33c268e1505371a5477"),
    "bindata" : BinData(0,"SGVsbG8=")
}

因此您的字符串现在已在您的文档中编码为 BSON 二进制类型。

请注意,它始终是编码字节而不是原始字节,因为 BSON 规范就是这样做的。