PyThon简单爬虫
该程序第一部分对新浪上网页链接进行爬取,第二部分对京东上指定页面的图片进行爬取
import re
import urllib.request
def 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 re
import urllib.request
import os,stat
def 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+=1
for i in range(1,10):
url="http://list.jd.com/list.html?cat=9987,653,655&page="+str(i)
craw(url,i)