基于Python的简单爬虫
发布日期:2021-05-07 22:59:46 浏览次数:17 分类:原创文章

本文共 2003 字,大约阅读时间需要 6 分钟。

PyThon简单爬虫

该程序第一部分对新浪上网页链接进行爬取,第二部分对京东上指定页面的图片进行爬取

	import reimport urllib.requestdef getlink(url):#设置请求头    headers=("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0")#自定义opener    opener = urllib.request.build_opener() #建立opener    opener.addheaders = [headers] #附加请求头    #global opener    urllib.request.install_opener(opener) #启用自定义opener#调用openerdirector    file=urllib.request.urlopen(url)#读取数据    data=str(file.read())#建立正则式匹配网页连接    pat='(https?://[^\s)";]+\.(\w|/)*)'    link=re.compile(pat).findall(data)#对连接进行去重    link=list(set(link))    return link#初始资源定位符url="http://news.sina.com.cn/"#获取连接linklist=getlink(url)大一连接for link in linklist:    print(link[0])    import reimport urllib.requestimport os,statdef craw(url,page):#读取url的内容并存于html1    html1=urllib.request.urlopen(url).read()    html1=str(html1)#第一个正则表达式,用于选取目标所在范围    pat1='<div id="J_selector".+?<div  class="J_selectorLine s-line">'    result1=re.compile(pat1).findall(html1)    result1=result1[0]#第二个正则表达式,用于匹配目标    pat2='<img src="//(.+?width="102" height="36">)'    imagelist=re.compile(pat2).findall(result1)    x=1    file_path='D:/img' #文件存储路径    for imageurl in imagelist:#文件名        imagename=str(page)+'_'+str(x)#文件网络地址        imageurl="https://"+imageurl        imageurl=imageurl.replace('" width="102" height="36">','')#读取文件格式        file_suffix=os.path.splitext(imageurl)[1]        print(file_suffix)#完整文件路径        filename = '{}{}{}{}'.format(file_path,os.sep,imagename,file_suffix)        print(filename)        try:#如果不存在文件路径则建立文件            if not os.path.exists(file_path):                os.makedirs(file_path)#下载文件            urllib.request.urlretrieve(imageurl,filename=filename)#错误处理        except IOError as e:            print("IOError")        except Exception as e:            print("Exception")        x+=1for i in range(1,10):    url="http://list.jd.com/list.html?cat=9987,653,655&page="+str(i)    craw(url,i)
上一篇:软件安全实验——缓存溢出
下一篇:椭圆曲线密码系统——椭圆曲线

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2025年03月21日 14时15分14秒