python beautifulSoup4 解析网页内容

1.使用pip如何安装模块

pip.exe 在python 安装路径下的Scripts目录下 ,
cmd cd 到该文件目录下 使用命令
如 :安装beautifulSoup4

pip  install  beautifulSoup4

2.python 多行注释(编辑器不同有差异)

IDE Pycharm :Ctrl+斜线

3.使用beautifulSoup4 爬取图片且把图片下载到本地,名字为文件名的img 的alt值

# coding=utf-8
import  urllib2
from bs4 import BeautifulSoup
import  urllib

url ="http://www.158pic.com/picture/scenery/fengjing/189488.htm"
response=urllib2.urlopen(url)
r=response.read()
r=r.decode('GB2312')
#print r

soup=BeautifulSoup(r,'html.parser')
print '获取图片的alt属性'

print soup.find_all('img')[1].attrs['alt'] #从索引0开始
print soup.find_all('img')[1].attrs['src']#
print soup.find_all('img')
length=len(soup.find_all('img'))
d=soup.find_all('img')
print length
for x in range(length):
    print x
    if(d[x].attrs.has_key('alt')):

        print d[x].attrs['src'], d[x].attrs['alt']
        urllib.urlretrieve(d[x].attrs['src'],'F:\\images\\'+d[x].attrs['alt']+'.jpg')
        print 'successful'

if(d[x].attrs.has_key('alt')): 因为attrs获取的是一个dict(类似于java的map集合) 需要先去判断属性alt是否存在
不然在 print d[x].attrs['src'], d[x].attrs['alt']会报错

这里写图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值