如何从URL添加图片到docx python?

时间:2017-08-07 11:33:38

标签: python python-2.7 web-scraping beautifulsoup python-docx

我在使用Python Docx库时遇到问题,我从网站上删除了图片,我想将它们添加到docx但是我无法直接将图像添加到docx,我一直收到错误:

  

文件“C:\ Python27 \ lib \ site-packages \ docx \ image \ image.py”,第46行,   从文件       open(path,'rb')为f:IOError:[Errno 22]无效模式('rb')或文件名:   'http://upsats.com/Content/Product/img/Product/Thumb/PCB2x8-.jpg'

这是我的代码:

import urllib
import requests
from bs4 import BeautifulSoup
from docx import Document
from docx.shared import Inches
import os


    document = Document()

    document.add_heading("Megatronics Items Full Search", 0)


    FullPage = ['New-Arrivals-2017-6', 'Big-Sales-click-here', 'Arduino-Development-boards',
                'Robotics-and-Copters', 'Breakout-Boards', 'RC-Wireless-communication', 'GSM,-GPS,-RFID,-Wifi',
                'Advance-Development-boards-and-starter-Kits', 'Sensors-and-IMU', 'Solenoid-valves,-Relays,--Switches',
                'Motors,-drivers,-wheels', 'Microcontrollers-and-Educational-items', 'Arduino-Shields',
                'Connectivity-Interfaces', 'Power-supplies,-Batteries-and-Chargers', 'Programmers-and-debuggers',
                'LCD,-LED,-Cameras', 'Discrete-components-IC', 'Science-Education-and-DIY', 'Consumer-Electronics-and-tools',
                'Mechanical-parts', '3D-Printing-and-CNC-machines', 'ATS', 'UPS', 'Internal-Battries-UPS',
                'External-Battries-UPS']

    urlp1 = "http://www.arduinopak.com/Prd.aspx?Cat_Name="
    URL = urlp1 + FullPage[0]

    for n in FullPage:
        URL = urlp1 + n
        page = urllib.urlopen(URL)
        bsObj = BeautifulSoup(page, "lxml")
        panel = bsObj.findAll("div", {"class": "panel"})

        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'})

            r = requests.get("http://upsats.com/", stream=True)
            data = r.text

            for link in imageList.find_all('img'):
                image = link.get("src")
                image_name = os.path.split(image)[1]
                r2 = requests.get(image)
                with open(image_name, "wb") as f:
                    f.write(r2.content)

                print(titleList.get_text(separator=u' '))
                print(imageList.get_text(separator=u''))
                print(descList.get_text(separator=u' '))
                document.add_heading("%s \n" % titleList.get_text(separator=u' '))
                document.add_picture(image, width=Inches(1.5))
                document.add_paragraph("%s \n" % descList.get_text(separator=u' '))

    document.save('megapy.docx')

不是全部,只是主要部分。现在,我在复制我下载的图片时遇到问题,我想将其复制到docx。我不知道如何添加图片。我该如何转换它?我想我必须格式化它,但我该怎么做?

我所知道的是问题在于此代码:

document.add_picture(image, width=Inches(1.0))

如何通过网址在docx中显示此图片?我错过了什么?

1 个答案:

答案 0 :(得分:3)

<强>更新

我用10张图片做了一个测试,我得到了一个docx。当加载很多我在一个地方有一个错误,我通过添加尝试覆盖了,除了(见下文)。由此产生的megapy.docx大165 MB,创建大约需要10分钟。

with open(image_name, "wb") as f:
    f.write(r2.content)

要:

image = io.BytesIO(r2.content)

并补充道:

try:
    document.add_picture(image, width=Inches(1.5))
except:
    pass

enter image description here

使用io库创建类似文件的对象。

适用于python2&amp; 3的示例:

import requests
import io
from docx import Document
from docx.shared import Inches

url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Usain_Bolt_Rio_100m_final_2016k.jpg/200px-Usain_Bolt_Rio_100m_final_2016k.jpg'
response = requests.get(url, stream=True)
image = io.BytesIO(response.content)

document = Document()
document.add_picture(image, width=Inches(1.25))
document.save('demo.docx')

enter image description here