分析html利器--Beautiful Soup

7 篇文章 0 订阅

最近公司搞图文编辑器,已经差不多了。还差一个一键发布到微信,这个功能本身简单,微信接口都有,只有一个要将图片上传到微信然后替换里面图片的链接有点麻烦。当然说这个麻烦是指不用Beautiful Soup的话。

先安装,使用pip直接安装,建议安装beautifulsoup4。

安装完后直接搞起:

from bs4 import BeautifulSoup

html_doc = '''
<html>
 <head>
 </head>
 <body>
  <p class="z_p" style="margin-top: 5px; margin-bottom: 5px; line-height: 2em;">
   我是正文。。。。。。
   <img class="z_img" src="http://qn.media.xxx.com/1.png" style="width: 100%; "/>
  </p>
  <p class="z_p" style="margin-top: 5px; margin-bottom: 5px; line-height: 2em;">
   <img class="z_img" src="http://qn.media.xxx.com/2.png" style="width: 100%;"/>
  </p>
 </body>
</html>
'''
soup = BeautifulSoup(html_doc)
# 查看soup内容
print soup.prettify()
# 查出所有img标签,得到一个数组
imgs = soup.find_all('img')
[<img class="z_img" src="http://qn.media.xxx.com/1.png" style="width: 100%; "/>, <img class="z_img" src="http://qn.media.xxx.com/2.png" style="width: 100%;"/>]
# 循环替换src, upload_weixin()函数为我自己定义函数,你可以简单做个替换
def upload_weixin(src):
    return 'weixin_uri%s' % src
for img in imgs:
    src = img.attrs.get('src')
    res = upload_weixin(src)
    img.attrs['src'] = res.get('url')
print soup.prettify()
是否img标签内的src被替换了呢?

参考:
https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
http://mp.weixin.qq.com/wiki/10/10ea5a44870f53d79449290dfd43d006.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值