Skip to main content
 首页 » 编程设计

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

2025年05月04日38傻小

假设我有这两行:

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

我是 Python 的新手,正在寻找一种方法来将存储在 html 中的 HTML 代码转换为二进制数组,这样我就可以轻松地存储在我的 MongoDB 中,而不必担心代码的编码问题我下载的网页。

建议?

请您参考如下方法:

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 规范就是这样做的。