urllib.request例子
python3.5不同于python2.7,在python3.5中,编写爬虫小程序,需要安装模块urllib下的request和parse类
小程序1:编写脚本,用来实现抓取百度贴吧指定页面
import urllib.parse #主要用来解析url
import urllib.request #主要用于打开和阅读url
import os,re
import urllib.error #用于错误处理
print("模拟抓取百度贴吧python和java页面,并写入指定路径文件")
def tieba_baidu(url,l):
#伪装成浏览器
header={'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'}
for i in range(len(l)):
file_name="G:/test/"+l[i]+".html"
print("正在下载"+l[i]+"页面,并保存为"+file_name)
m=urllib.request.urlopen(url+l[i],headers=header).read()
with open(file_name,"wb") as file:
file.write(m)
if __name__=="__main__":
url="http://tieba.baidu.com/f?kw="
l_tieba=["python","java","c#"]
tieba_baidu(url,l_tieba)
小程序二:爬取指定页面指定格式的文件(本例子爬取指定页面的jpg文件)
print("爬取指定页面的jp格式的文件")
def baidu_tieba(url,l):
"""
根据传入的地址和关键字列表进行图片抓取
"""
for i in range(len(l)):
count=1
file_name="G:/test/"+l[i]+".html"
print("正在下载"+l[i]+"页面,并保存为"+file_name)
m=urllib.request.urlopen(url+l[i]).read()
#创建目录保存每个网页上的图片
dirpath="G:/test/"
dirname=l[i]
new_path=os.path.join(dirpath,dirname)
if not os.path.isdir(new_path):
os.makedirs(new_path)
page_data=m.decode()
page_image=re.compile('<img src=\"(.+?)\"') #匹配图片的pattern
for image in page_image.findall(page_data):#page_image.findall(page_data)用正则表达式匹配所有的图片
pattern=re.compile(r'http://.*.jpg$') #匹配jpg格式的文件
if pattern.match(image): #如果匹配,则获取图片信息,若不匹配,进行下一个页面的匹配
try:
image_data=urllib.request.urlopen(image).read() #获取图片信息
image_path=dirpath+dirname+"/"+str(count)+".jpg" #给图片命名
count+=1
print(image_path) #打印图片路径
with open(image_path,"wb") as image_file:
image_file.write(image_data) #将图片写入文件
except urllib.error.URLError as e:
print("Download failed")
with open(file_name,"wb") as file: #将页面写入文件
file.write(m)
if __name__=="__main__":
url="http://tieba.baidu.com/f?kw="
l_tieba=["python","java","c#"]
baidu_tieba(url,l_tieba)