【问题标题】:how to scraep text and image together?如何将文本和图像刮到一起?
【发布时间】:2013-08-26 19:00:55
【问题描述】:

我正在使用 beautifulSoup4 开发网页抓取工具。我想获取文章的文字和图片,但是有一些问题! html代码是这样的:

<div>
 some texts1
 <br />
 <img src="imgpic.jpg" />
 <br />
 some texts2
</div>

我得到了整个文本:

post_soup.get_text()

并像往常一样将所有图像保存在divurllib2 最后我将它们保存在一个html页面中,最后将所有文本和图像放在顶部,但我想将它们保存在新的html页面中,就像我抓取它们的页面一样,我的意思是首先some texts1然后image然后@987654327 @

有什么建议吗?

【问题讨论】:

    标签: python-2.7 web-scraping beautifulsoup


    【解决方案1】:

    这不是最好和正确的方法,但应该可以:

    from bs4 import BeautifulSoup
    
    html = "<div>\
     some texts1\
     <br />\
     <img src=\"imgpic.jpg\" />\
     <br />\
     some texts2\
    </div>"
    
    soup = BeautifulSoup(html)
    text = "+".join(soup.stripped_strings).split("+")
    
    print text[0]
    print soup.find("img")['src']
    print text[1]
    

    输出:

    some texts1
    imgpic.jpg
    some texts2
    

    【讨论】:

    • +1 怎么会更好?它正确地在顶部/底部获取多行字符串。
    【解决方案2】:

    我不会使用get_text(),而是使用prettify() 将您想要的整个&lt;div&gt; 部分作为字符串返回。这样,您始终可以保证在顶部和底部有正确的文本。从那里你可以剥离部分字符串以获得你想要的:

    # post_soup is the <div> element you posted
    s = post_soup.prettify()
    split_s = s.split('<br/>')
    top = split_s[0].strip('<div>')
    bottom = split_s[-1].strip('</div>')
    

    输出:

    >>> top
    u'\n some texts1\n '
    >>> bottom
    u'\n some texts2\n'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      • 2019-12-14
      • 2015-01-26
      • 2020-02-13
      相关资源
      最近更新 更多