163
社区成员
本实验将利用python程序抓取网络图片,完成可以批量下载一个网站的照片。所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地。
8学时。
1、网络爬虫
即Web Spider,网络蜘蛛是通过网页的链接地址来寻找网页的。从网站某一个页面(通常是首页)开始,读取网页的内容,找到在网页中的其它链接地址,然后通过这些链接地址寻找下一个网页,这样一直循环下去,直到把这个网站所有的网页都抓取完为止。
网络爬虫的基本操作是抓取网页。
2、浏览网页过程
抓取网页的过程其实和读者平时使用浏览器浏览网页的道理是一样的。打开网页的过程其实就是浏览器作为一个浏览的“客户端”,向服务器端发送了 一次请求,把服务器端的文件“抓”到本地,再进行解释、展现。浏览器的功能是将获取到的HTML代码进行解析,然后将原始的代码转变成我们直接看到的网站页面。
URL的格式由三部分组成:
第一部分和第二部分用“://”符号隔开,
第二部分和第三部分用“/”符号隔开。
第一部分和第二部分是不可缺少的,第三部分有时可以省略。
爬虫最主要的处理对象就是URL,它根据URL地址取得所需要的文件内容,然后对它 进行进一步的处理。
因此,准确地理解URL对理解网络爬虫至关重要。
3、利用urllib2通过指定的URL抓取网页内容
在Python中,我们使用urllib2这个组件来抓取网页。
urllib2是Python的一个获取URLs(Uniform Resource Locators)的组件。
它以urlopen函数的形式提供了一个非常简单的接口。
4、HTTP的异常处理问题
当urlopen不能够处理一个response时,产生urlError。
不过通常的Python APIs异常如ValueError,TypeError等也会同时产生。
HTTPError是urlError的子类,通常在特定HTTP URLs中产生。
代码提供的网站没了,就随便写了一个爬虫,看看就好,问题很多,不提供测试网站
import requests
import re
import time
class sinffer():
def __init__(self,url,pic_path,download_url,re_func,download_format,get_augment=None):
self.url = url
self.pic_path = pic_path
self.dtu = download_url
self.pic_list = set()
self.re_func = re_func
self.download_format = download_format
self.s = requests.session()
self.get_augment = get_augment
self.download_url_list = set()
def Get_Pic_CT(self):
round = 5
r = self.s.get(self.url)
syntax = re.compile(self.re_func,re.I|re.S|re.M)
list_pics_tmp = syntax.findall(r.text)
self.pic_list.update(set(list_pics_tmp))
if self.get_augment != None:
while round !=1 :
time.sleep(0.5)
r = self.s.get(self.url+self.get_augment+str(round))
print(self.url+self.get_augment+str(round))
list_pics_tmp = syntax.findall(r.text)
self.pic_list.update(set(list_pics_tmp))
round = round - 1
def get_url_of_pic(self):
syntax_download = re.compile(self.download_format,re.I|re.S|re.M)
for i in self.pic_list:
try:
download_url = self.dtu + i
r = syntax_download.findall(self.s.get(download_url).text)
if len(r) != 0:
self.download_url_list.add(r[0])
time.sleep(0.5)
except :
print('some Thing Wrong when download %s,skip'%i)
def download_image(self):
time.sleep(1)
n = 1
for i in self.download_url_list:
try:
with open('%s/%s.%s'%(self.pic_path,str(n),i[-3:]),'wb') as f:
r = self.s.get(i).content
f.write(r)
f.close()
n = n+1
except:
print('some Thing Wrong when download %s,skip'%i)
#src=""
if __name__=='__main__':
url = '' #不提供
pic_path = 'pic'
download_url = '' #不提供
re_fun = r'' #不提供
download_format = r'' #不提供
get_augment = '' #不提供
t = sinffer(url, pic_path, download_url,re_fun,download_format,get_augment=get_augment)
t.Get_Pic_CT()
t.get_url_of_pic()
t.download_image()
结果如下,仅作参考