繁体   English   中英

Python Beautifulsoup:如何从div下载图像,然后将其复制到Word文档?

[英]Python Beautifulsoup: How to download images from a div and then copy it to word document?

这是我的代码:

    for div in panel:
    titleList = div.find('div', attrs={'class': 'panel-heading'})
    imageList = div.find('div', attrs={'class', 'pro-image'})
    descList = div.find('div', attrs={'class': 'pro-desc'})
    print titleList.get_text(separator=u' ')
    print descList.get_text(separator=u' ')
    document.add_heading("%s \t \n" % titleList.get_text(separator=u'  '), level=1)
    document.add_paragraph("%s \t \n" % descList.get_text(separator=u'  '))

我想从以下位置下载图像:

imageList = div.find('div', attrs={'class', 'pro-image'})

然后,我想复制那些下载的图像并将其复制到Word文档中。 我该怎么做呢?

您可以使用请求下载图像,然后以适当的扩展名将其保存为二进制数据。

假设您的图片位于http://example/my_image.jpg

with open("my_image.jpg", "wb") as img_handle:
    img_data = requests.get("http://example/my_image.jpg")
    img_handle.write(img_data.content)

不过,这只是一个简单的例子。 正如tmadam在评论中指出的那样 ,对于二进制数据,应使用img_data.content而不是img_data.text

至于将该图像插入Word文档,则可以使用提供这种功能的任何库。 python-docx作为第一个Google搜索结果出现,它可能很有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM