Python爬虫入门

来源:互联网 发布:黄金原油看盘软件 编辑:程序博客网 时间:2024/06/06 08:08

近期自学了Python爬虫,跟大家分享一下如何通过Python爬虫爬到贴吧中所有图片以及网页代码。

普及一下网页状态码、网页编码的意思:

网页状态码:200(正常访问)301(重定向)403(禁止访问)404(网页不存在)500(服务器忙),我们经常访问外网或者不存在的网站遇到的就是403以及404错误。

网页编码:是指在网页总特定的字符编码格式的库,例如常见的utf-8、GBK、gb 2312等,代码不同的编码格式,utf-8因为其可以在统一显示不同语言,故现如今较为通用。

接下来先来介绍一下如何访问网站,并将其网页爬取下来。

环境:Python2.7编辑器:Sublime Text3库:urllib,urllib2,re(正则表达式),BeautifulSoup,库安装可通过:pip install --完成自动安装(若没安装pip,百度一下教程)。
一:爬取网站代码并下载到指定路径
# -*-coding:utf-8 -*-#导入库函数并读取URLimport urlliburl = "http://www.baidu.com/"html = urllib.urlopen(url)##读取百度网页代码print html.read()##读取百度网页状态码print html.getcode()html.close()
##保存当前页面至桌面
urllib.urlretrieve(url2,"C:\\USers\\Administrator\\Desktop\\baidu.html")

二:爬取网站代码并下载到指定路径
       爬取贴吧图片时我们需先看一下该贴吧审查元素


如上图所示通过审查元素后,我们可以看到网页代码中定义图片图片类型class:BDE_Image,后面定义src为---.jpg,故我们可以根据这些特性对其进行编程实现保存该贴吧中所有图片:
1:使用正则表达式方法
# -*- coding:utf-8 -*-import re #正则表达式import urllibdef get_content(url):"""doc."""html = urllib.urlopen(url)content= html.read()html.close()return contentdef get_images(info):"""doc.<img class="j_retract" id="big_img_1501662059644" src="http://imgsrc.baidu.com/forum/w%3D580%3B/sign=0cf15dc417178a82ce3c7fa8c638728d/f3d3572c11dfa9ec04c4f11f6bd0f703908fc1d4.jpg" onerror="this.src='//tb2.bdstatic.com/tb/static-frs/img/v2/picerr.gif';this.width=82;this.height=75;" style="width: 534px; height: 534px; visibility: visible;">j_retract"""regex = r'class="BDE_Image" src="(.+?\.jpg)"'##编译正则表达式pat = re.compile(regex)image_code = re.findall(pat,info)#print image_codei = 0for image_url in image_code:print image_urlurllib.urlretrieve(image_url,'%s.jpg' % i)i+=1info =  get_content('https://tieba.baidu.com/p/3823765471')print info##print get_images(info)
2:使用BeautifulSoup
# -*- coding:utf-8 -*-import urllibfrom bs4 import BeautifulSoupdef get_content(url):html = urllib.urlopen(url)content = html.read()html.close()return content#<img class="BDE_Image" src="https://imgsa.baidu.com/forum/w%3D580/sign=f9cf09409c25bc312b5d01906ede8de7/8f0ede0735fae6cdafb377ef0ab30f2443a70fda.jpg" pic_ext="jpeg" changedsize="true" width="560" height="497">def get_images(info):soup = BeautifulSoup(info)all_img = soup.find_all('img',class_="BDE_Image")#第二个参数为属性,可得到特定格式x = 1##保存图像for img in all_img:#print img['src']image_name = '%s.jpg' % xurllib.urlretrieve(img['src'],image_name)x+=1info = get_content('https://tieba.baidu.com/p/3823765471')get_images(info
通过这样的方法即可将贴吧中图片保存到本地文件夹
此时你应该熟悉utllib.urlopen(),read(),urllib.urlretrieve()的作用了,分别是打开网址、读取该网址代码以及保存网址指定文件。

其中所有代码已上传至:http://download.csdn.net/detail/dream__tt/9919725