019年4月16日零基础入门Python,第二天就给自己找了一个任务,做网站文章的爬虫小项目,因为实战是学代码的最快方式。所以从今天起开始写Python实战入门系列教程,也建议大家学Python时一定要多写多练。
一,首先看看Python是如何简单的爬取网页的
1,准备工作
项目用的BeautifulSoup4和chardet模块属于三方扩展包,如果没有请自行pip安装,我是用pycharm来做的安装,下面简单讲下用pycharm安装chardet和BeautifulSoup4
二,由浅入深,我们先抓取网页
我们这里以抓取简书首页为例:http://www.jianshu.com/
# 简单的网络爬虫 from urllib import request import chardet response = request.urlopen("http://www.jianshu.com/") html = response.read() charset = chardet.detect(html)# {'language': '', 'encoding': 'utf-8', 'confidence': 0.99} html = html.decode(str(charset["encoding"])) # 解码 print(html)
由于抓取的html文档比较长,这里简单贴出来一部分给大家看下
<!DOCTYPE html> <!--[if IE 6]><html class="ie lt-ie8"><![endif]--> <!--[if IE 7]><html class="ie lt-ie8"><![endif]--> <!--[if IE 8]><html class="ie ie8"><![endif]--> <!--[if IE 9]><html class="ie ie9"><![endif]--> <!--[if !IE]><!--> <html> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no"> <!-- Start of Baidu Transcode --> <meta http-equiv="Cache-Control" content="no-siteapp" /> <meta http-equiv="Cache-Control" content="no-transform" /> <meta name="applicable-device" content="pc,mobile"> <meta name="MobileOptimized" content="width"/> <meta name="HandheldFriendly" content="true"/> <meta name="mobile-agent" content="format=html5;url=http://localhost/"> <!-- End of Baidu Transcode --> <meta name="description" content="简书是一个优质的创作社区,在这里,你可以任性地创作,一篇短文、一张照片、一首诗、一幅画……我们相信,每个人都是生活中的艺术家,有着无穷的创造力。"> <meta name="keywords" content="简书,简书官网,图文编辑软件,简书下载,图文创作,创作软件,原创社区,小说,散文,写作,阅读"> ..........后面省略一大堆
这就是Python3的爬虫简单入门,是不是很简单,建议大家多敲几遍
三,Python3爬取网页里的图片并把图片保存到本地文件夹
目标
import re import urllib.request #爬取网页html def getHtml(url): page = urllib.request.urlopen(url) html = page.read() return html html = getHtml("http://tieba.baidu.com/p/3205263090") html = html.decode('UTF-8') #获取图片链接的方法 def getImg(html): # 利用正则表达式匹配网页里的图片地址 reg = r'src="([.*\S]*\.jpg)" pic_ext="jpeg"' imgre=re.compile(reg) imglist=re.findall(imgre,html) return imglist imgList=getImg(html) imgCount=0 #for把获取到的图片都下载到本地pic文件夹里,保存之前先在本地建一个pic文件夹 for imgPath in imgList: f=open("../pic/"+str(imgCount)+".jpg",'wb') f.write((urllib.request.urlopen(imgPath)).read()) f.close() imgCount+=1 print("全部抓取完成")
迫不及待的看下都爬取到了些什么美图
就这么轻易的爬取到了24个妹子的图片。是不是很简单。
四,Python3爬取新闻网站新闻列表
到这里稍微复杂点,就分布给大家讲解
分析上图我们要抓取的信息再div中的a标签和img标签里,所以我们要想的就是怎么获取到这些信息
这里就要用到我们导入的BeautifulSoup4库了,这里的关键代码
# 使用剖析器为html.parser soup = BeautifulSoup(html, 'html.parser') # 获取到每一个class=hot-article-img的a节点 allList = soup.select('.hot-article-img')
上面代码获取到的allList就是我们要获取的新闻列表,抓取到的如下
[<div class="hot-article-img"> <a href="/article/211390.html" target="_blank">  </a> </div>, <div class="hot-article-img"> <a href="/article/214982.html" target="_blank" title="TFBOYS成员各自飞,商业价值天花板已现?"> <!--视频和图片保留一个-->  </a> </div>, <div class="hot-article-img"> <a href="/article/213703.html" target="_blank" title="买手店江湖"> <!--视频和图片保留一个-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214679.html" target="_blank" title="iPhone X正式告诉我们,手机和相机开始分道扬镳"> <!--视频和图片保留一个-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214962.html" target="_blank" title="信用已被透支殆尽,乐视汽车或成贾跃亭弃子"> <!--视频和图片保留一个-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214867.html" target="_blank" title="别小看“搞笑诺贝尔奖”,要向好奇心致敬"> <!--视频和图片保留一个-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214954.html" target="_blank" title="10 年前改变世界的,可不止有 iPhone | 发车"> <!--视频和图片保留一个-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214908.html" target="_blank" title="感谢微博替我做主"> <!--视频和图片保留一个-->  </a> </div>, <div class="hot-article-img"> <a href="/article/215001.html" target="_blank" title="苹果确认取消打赏抽成,但还有多少内容让你觉得值得掏腰包?"> <!--视频和图片保留一个-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214969.html" target="_blank" title="中国音乐的“全面付费”时代即将到来?"> <!--视频和图片保留一个-->  </a> </div>, <div class="hot-article-img"> <a href="/article/214964.html" target="_blank" title="百丽退市启示录:“一代鞋王”如何与新生代消费者渐行渐远"> <!--视频和图片保留一个-->  </a> </div>]
这里数据是抓取到了,但是太乱了,并且还有很多不是我们想要的,下面就通过遍历来提炼出我们的有效信息
#遍历列表,获取有效信息 for news in allList: aaa = news.select('a') # 只选择长度大于0的结果 if len(aaa) > 0: # 文章链接 try:#如果抛出异常就代表为空 href = url + aaa[0]['href'] except Exception: href='' # 文章图片url try: imgUrl = aaa[0].select('img')[0]['src'] except Exception: imgUrl="" # 新闻标题 try: title = aaa[0]['title'] except Exception: title = "标题为空" print("标题",title,"\nurl:",href,"\n图片地址:",imgUrl) print("==============================================================================================")
这里添加异常处理,主要是有的新闻可能没有标题,没有url或者图片,如果不做异常处理,可能导致我们爬取的中断。
过滤后的有效信息
标题 标题为空 url: https://www.huxiu.com/article/211390.html 图片地址: https://img.huxiucdn.com/article/cover/201708/22/173535862821.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 标题 TFBOYS成员各自飞,商业价值天花板已现? url: https://www.huxiu.com/article/214982.html 图片地址: https://img.huxiucdn.com/article/cover/201709/17/094856378420.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 标题 买手店江湖 url: https://www.huxiu.com/article/213703.html 图片地址: https://img.huxiucdn.com/article/cover/201709/17/122655034450.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 标题 iPhone X正式告诉我们,手机和相机开始分道扬镳 url: https://www.huxiu.com/article/214679.html 图片地址: https://img.huxiucdn.com/article/cover/201709/14/182151300292.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 标题 信用已被透支殆尽,乐视汽车或成贾跃亭弃子 url: https://www.huxiu.com/article/214962.html 图片地址: https://img.huxiucdn.com/article/cover/201709/16/210518696352.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 标题 别小看“搞笑诺贝尔奖”,要向好奇心致敬 url: https://www.huxiu.com/article/214867.html 图片地址: https://img.huxiucdn.com/article/cover/201709/15/180620783020.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 标题 10 年前改变世界的,可不止有 iPhone | 发车 url: https://www.huxiu.com/article/214954.html 图片地址: https://img.huxiucdn.com/article/cover/201709/16/162049096015.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 标题 感谢微博替我做主 url: https://www.huxiu.com/article/214908.html 图片地址: https://img.huxiucdn.com/article/cover/201709/16/010410913192.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 标题 苹果确认取消打赏抽成,但还有多少内容让你觉得值得掏腰包? url: https://www.huxiu.com/article/215001.html 图片地址: https://img.huxiucdn.com/article/cover/201709/17/154147105217.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 标题 中国音乐的“全面付费”时代即将到来? url: https://www.huxiu.com/article/214969.html 图片地址: https://img.huxiucdn.com/article/cover/201709/17/101218317953.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ============================================================================================== 标题 百丽退市启示录:“一代鞋王”如何与新生代消费者渐行渐远 url: https://www.huxiu.com/article/214964.html 图片地址: https://img.huxiucdn.com/article/cover/201709/16/213400162818.jpg?imageView2/1/w/280/h/210/|imageMogr2/strip/interlace/1/quality/85/format/jpg ==============================================================================================
到这里我们抓取新闻网站新闻信息就大功告成了,下面贴出来完整代码
from bs4 import BeautifulSoup from urllib import request import chardet url = "https://www.huxiu.com" response = request.urlopen(url) html = response.read() charset = chardet.detect(html) html = html.decode(str(charset["encoding"])) # 设置抓取到的html的编码方式 # 使用剖析器为html.parser soup = BeautifulSoup(html, 'html.parser') # 获取到每一个class=hot-article-img的a节点 allList = soup.select('.hot-article-img') #遍历列表,获取有效信息 for news in allList: aaa = news.select('a') # 只选择长度大于0的结果 if len(aaa) > 0: # 文章链接 try:#如果抛出异常就代表为空 href = url + aaa[0]['href'] except Exception: href='' # 文章图片url try: imgUrl = aaa[0].select('img')[0]['src'] except Exception: imgUrl="" # 新闻标题 try: title = aaa[0]['title'] except Exception: title = "标题为空" print("标题",title,"\nurl:",href,"\n图片地址:",imgUrl) print("==============================================================================================")
数据获取到了我们还要把数据存到数据库,只要存到我们的数据库里,数据库里有数据了,就可以做后面的数据分析处理,也可以用这些爬取来的文章,给app提供新闻api接口,当然这都是后话了,等我自学到Python数据库操作以后,会写一篇文章
《Python3实战入门数据库篇---把爬取到的数据存到数据库》
编程小石头,为分享干货而生!据说,每个年轻上进,颜值又高的互联网人都关注了编程小石头。
索 HTML 图像的不同概念,以及如何有效地使用它们在您的网站上增加视觉吸引力、传达信息和表达情感。 本指南包含大量示例和实用技巧,可帮助您创建一个视觉效果惊人且用户友好的网站。
图像是网页设计师和开发人员的强大工具,它们可用于传达信息、表达情感并使网站更具视觉吸引力。 HTML 图像概念是网页设计和开发的重要方面。 它们用于将图像嵌入到网页中,以便于显示和共享图片和图形。 在这篇博文中,我们将探讨 HTML 图像的不同概念以及如何有效地使用它们。
首先,让我们谈谈不同类型的 HTML 图像。 有两种主要类型的图像:内嵌图像和背景图像。 内联图像直接嵌入到 HTML 代码中,而背景图像则应用于元素的背景。
在此示例中,内联图像“image.jpg”直接嵌入到 HTML 代码中并显示给用户。
在此示例中,背景图像“image.jpg”应用于 div 元素的背景并显示给用户。
以合乎逻辑且一致的方式使用图像也很重要。 这意味着您应该使用它们来传达与网页内容相关的信息或表达情感,而不是随意使用它们。 此外,使用 alt 属性为图像添加文本替代也很重要,它允许可能使用屏幕阅读器的用户访问图像,或者以防图像加载失败。
在此示例中,替代文本“日落的美丽图像”让用户清楚地了解图像所代表的内容。
另一个 HTML 图像概念是使用宽度和高度属性调整图像大小的能力。 这些属性允许您调整图像大小以适合您的布局和设计。
在此示例中,图像的宽度设置为 300 像素,图像的高度设置为 200 像素。
HTML 图像概念是网页设计和开发的重要方面。 它们用于将图像嵌入到网页中,以便于显示和共享图片和图形。 通过了解不同类型的图像并正确使用它们,您可以为您的网站增加额外的视觉吸引力,并以有力的方式传达信息或表达情感。 无论是使用内联图片还是背景图片,添加替代文本或调整大小,这些概念都是创建视觉效果惊人且用户友好的网站的关键。
但不要只相信我们的话,您自己试试吧! 尝试使用 HTML 图像,看看它们如何增强您网站的整体外观。 通过每一行代码,您离创建一个您的访问者会喜欢的美观且引人入胜的网站又近了一步。 请记住,图像具有唤起情感和传达信息的力量,因此请明智地使用它们并将它们作为您网页设计策略的重要组成部分。 通过正确组合 HTML 和图像,您将创建一个脱颖而出并给访问者留下持久印象的网站。
作者:极客小俊」
「 把逻辑思维转变为代码的技术博主」
咱们废话不多说直接上代码案例素材!
首先准备图片素材 放入到你的demo案例下的img文件夹
当然图片你也可以用其他类似的图来代替也是可以的!
如图
<div id="big">
<div class="box">
<div class="pic"><img src="img/bag.jpg" alt="" title=""/></div>
<div class="mask">
<h2>三用小巧思波士顿包</h2>
<p>印花波士顿包 复古波士顿包,手提单肩斜挎多用,印花PVC</p>
</div>
<div class="title">
<h2 class="sl"><span></span>全场2折起 印花波士顿包 专柜终身保养</h2>
<h3 class="sl"><i></i><span>抢全场2件88折</span>新款蜜蜂系列印花手提斜挎包</h3>
<div class="price">
<div class="zx_pr"><span>¥</span>659</div>
<div class="xl_yp">
<p><del>¥1998.00</del><span>退货赔运费</span></p>
<p><strong>70</strong>件已付款</p>
</div>
<div class="buy">抢!</div>
</div>
</div>
</div>
<div class="box">
<div class="pic"><img src="img/bag3.jpg" alt="" title=""/></div>
<div class="mask">
<h2>猪年纪念款经典牛皮水桶包</h2>
<p>猪年纪念款 经典牛皮水桶包,自带强大气场</p>
</div>
<div class="title">
<h2 class="sl"><span></span>全场2折起 印花波士顿包 专柜终身保养</h2>
<h3 class="sl"><i></i><span>抢全场2件88折</span>新款蜜蜂系列印花手提斜挎包</h3>
<div class="price">
<div class="zx_pr"><span>¥</span>659</div>
<div class="xl_yp">
<p><del>¥1998.00</del><span>退货赔运费</span></p>
<p><strong>70</strong>件已付款</p>
</div>
<div class="buy">抢!</div>
</div>
</div>
</div>
<div class="box">
<div class="pic"><img src="img/bag4.jpg" alt="" title=""/></div>
<div class="mask">
<h2>一包四用蜜蜂系列迷你小方包</h2>
<p>四用方盒包 一包四用蜜蜂系列迷你链条小方包</p>
</div>
<div class="title">
<h2 class="sl"><span></span>全场2折起 印花波士顿包 专柜终身保养</h2>
<h3 class="sl"><i></i><span>抢全场2件88折</span>新款蜜蜂系列印花手提斜挎包</h3>
<div class="price">
<div class="zx_pr"><span>¥</span>659</div>
<div class="xl_yp">
<p><del>¥1998.00</del><span>退货赔运费</span></p>
<p><strong>70</strong>件已付款</p>
</div>
<div class="buy">抢!</div>
</div>
</div>
</div>
</div>
*{
padding:0px;
margin:0px;
}
body{
font-family: '微软雅黑';
}
.sl{
white-space: nowrap;
word-break: keep-all;
text-overflow: ellipsis;
}
#big{
width:950px;
height:416px;
margin:10px auto;
overflow: hidden;
}
#big>.box{
width:298px;
height:410px;
float: left;
position: relative;
overflow: hidden;
border:1px solid #ccc;
margin-left:19px;
}
#big>.box:first-child{
margin-left:0px;
}
#big>.box>.pic{
width:298px;
height:300px;
overflow: hidden;
}
#big>.box>.pic>img{
transition: all 500ms;
}
#big>.box:hover>.pic>img{
transform: scale(1.5);
}
#big>.box>.mask{
height:300px;
width:298px;
position: absolute;
left:-298px;
top:0px;
background:rgba(0,0,0,0.3);
transition: all 600ms;
color:#fff;
}
#big>.box>.mask>h2{
font-size: 18px;
margin:80px 0px 10px 10px;
}
#big>.box>.mask>p{
font-size: 12px;
margin:0px 0px 10px 10px;
}
#big>.box:hover>.mask{
left:0px;
}
#big>.box>.title>h2{
margin:10px auto;
width:288px;
height:20px;
line-height: 20px;
font-size: 14px;
color:#333;
overflow: hidden;
font-weight: normal;
}
#big>.box>.title>h2>span{
display: inline-block;
width:31px;
height:16px;
vertical-align: middle;
background: url('img/tu.png') no-repeat;
background-size:cover;
margin-right:5px;
}
#big>.box>.title>h3{
width:288px;
height:20px;
margin:0px auto;
font-size: 12px;
color:#666;
font-weight: 400;
}
#big>.box>.title>h3>i{
width:12px;
height:16px;
display: inline-block;
background:url('img/tu1.jpg') no-repeat;
vertical-align: middle;
}
#big>.box>.title>h3>span{
color:#f00;
margin:0 5px 0 5px;
}
#big>.box>.title>.price{
width:298px;
height:50px;
background:#e61414;
}
#big>.box>.title>.price>.zx_pr>span{
font-size: 20px;
}
#big>.box>.title>.price>.zx_pr{
width:83px;
height:50px;
line-height: 50px;
float: left;
margin-left:2px;
vertical-align: bottom;
font-size:38px;
color:#fff;
}
#big>.box>.title>.price>.buy{
width:56px;
height:50px;
line-height: 50px;
text-align: center;
background:url('img/tu3.png') no-repeat;
float:right;
color:#f00;
}
#big>.box>.title>.price>.xl_yp{
width:145px;
height:41px;
float: left;
margin:4px 0 0 8px;
font-size: 12px;
color:#fff;
}
#big>.box>.title>.price>.xl_yp>p>span{
margin-left:4px;
width:72px;
height:17px;
display: inline-block;
line-height: 17px;
text-align: center;
border-radius: 10px;
background:#ffb369;
}
#big>.box>.title>.price>.xl_yp>p:nth-child(2){
width:80px;
height:20px;
line-height: 20px;
text-align: center;
border-radius: 1px;
margin-top:5px;
background:rgba(0,0,0,0.2);
}
#big>.box>.title>.price>.xl_yp>p:nth-child(2)>strong{
margin-right: 5px;
font-size: 14px;
}
如图
"点赞" "✍️评论" "收藏"
大家的支持就是我坚持创作下去的动力!
如果以上内容有任何错误或者不准确的地方,欢迎在下面 留个言指出、或者你有更好的想法,欢迎一起交流学习❤️❤️❤️❤️❤️
*请认真填写需求信息,我们会在24小时内与您取得联系。