Q:

Converting an html page to binary format in python

Suppose I have these two lines:
c=urllib2.urlopen(myUrl)
html=c.read()

I'm quite new to Python and am looking for a way to transform the HTML code stored in html in a binary array so I could easily store in my MongoDB without worrying about the encoding of the webpage I downloaded.
Suggestions?

A:

The pymongo driver already has methods for importing strings as binary. Following with this example:
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()

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

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

So your string has been encoded to a BSON Binary type now in your document.
Note that it's always encoded bytes and not raw because that is how the BSON spec does it.

