python - 如何使用 beautiful soup 将爬取数据上传到 python 中的 AZURE BLOB STORAGE 中?

标签 python azure beautifulsoup azure-storage azure-blob-storage

我正在从 URL 抓取数据并使用 beautiful soup 进行抓取。我想将爬网数据作为 blob 存储到 AZURE BLOB STORAGE 中。下面是我在本地保存数据时的代码,我想执行相同的操作来直接上传到 Azure。

soup = BeautifulSoup(urlopen('www.abc.html')) 
outfile = open('C:\\Users\\ADMIN\\filename.txt','w') 
data = soup.encode("ascii","ignore") 
outfile.write(data) 
outfile.close

此代码成功将网站数据保存在我的本地文件夹中,请帮助我将同一网站的数据直接保存在azure blob存储中。我在 AZURE BLOB STORAGE 中有 key 和帐户。

soup=BeautifulSoup(urlopen('www.abc.html'))
data = soup.encode("ascii","ignore")        

block_blob_service.create_blob_from_text('containername', 'filename.txt', data)

我正在尝试上面的代码,但它不起作用。

最佳答案

没有任何信息显示 BeautifulSoup 的版本以及 urlopen 方法来自 urlliburllib2 > 或 Python 2 中的 urllib3。根据您的代码,根据我的经验,我认为您将 BeautifulSoup4urllib2 一起使用,并且我尝试重现有关 data 类型不是 str 的问题,但由于我的下面的代码有效而失败。

这是我的示例代码。

from bs4 import BeautifulSoup 
import urllib2

soup = BeautifulSoup(urllib2.urlopen("http://bing.com"))
data = soup.encode("ascii","ignore") 
print type(data) # It's <type 'str'> here

from azure.storage.blob.blockblobservice import BlockBlobService

block_blob_service = BlockBlobService(account_name='<your-account-name>', account_key='<your-account-key>')
block_blob_service.create_container('mycontainer')
block_blob_service.create_blob_from_text('mycontainer1', 'filename.txt', data)

即使我用 urllib 替换了 urllib2data 类型还是 str。 因此,我认为您可以尝试在代码中使用 StringIOblock_blob_service.create_blob_from_stream ,如下所示。

from StringIO import StringIO
block_blob_service.create_blob_from_stream('mycontainer', 'filename2.txt', StringIO(data))

它也适合我。

希望有帮助。

关于python - 如何使用 beautiful soup 将爬取数据上传到 python 中的 AZURE BLOB STORAGE 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45957408/

相关文章:

azure - 如何保护 Azure 网站和数据部署的安全

python - 在 Python 中查找大型文本文件中的字符串

python - 如何在直方图中绘制字典中的键和值

Azure CDN - 如何从根域重定向到 www?规则引擎中的某些规则不适用

python - 使用 BeautifulSoup 中的 nextSibling 什么都不输出

python - BeautifulSoup4/CSS选择器如何选择

python - 如何以编程方式下载 Python 中 blob 中引用的 m3u8 视频?

java - 在 Java 中使用 SWIG 类型映射

python - 如何在 Python 3 中的另一个文件夹中打开 Python 3 程序

wcf - Net Messaging 绑定(bind)轮询间隔和并发性