# -*- coding: utf-8 -*-
#title:抓取某網(wǎng)頁的所有鏈接并將鏈接編碼后放入各個(gè)文件夾內(nèi)
importre
importrequests
importsys
importos
#定義頁面鏈接榜苫,并抓取此頁面的網(wǎng)頁代碼
r = requests.get('https://www.chinabidding.cn/search/searchzbw/search2?rp=22&categoryid=1&keywords=%E8%BD%A8%E9%81%93%E4%BA%A4%E9%80%9A&page=1&areaid=&table_type=0&b_date=year');
#把代碼存入一個(gè)變量中
data = r.text
#print data;
#正則匹配需要抓取的鏈接
link_list =re.findall(r'target="_blank" href="(.+?\.html)',data)
#定義一個(gè)參數(shù)為0,方便循環(huán)編碼
i=0
#開始循環(huán)
for url in link_list:
? #循環(huán)參數(shù)
? i=i+1
? #將參數(shù)變?yōu)樽址奖闫唇?/p>
? ii ='%d'%i
? #在路徑下創(chuàng)建編碼的文件夾
? os.makedirs(r'd:/pythonWorkSpace/Python27PygamePy2exe-master/Python27PygamePy2exe-master/'+ii)
? #在目標(biāo)文件夾下打開一個(gè)html頁面并定于可以寫入
? f =file('d:/pythonWorkSpace/Python27PygamePy2exe-master/Python27PygamePy2exe- ?master/'+ii+'/'+ii+".html","w")
? #定義抓取的目標(biāo)頁面下的子鏈接的html代碼
? url='https://www.chinabidding.cn'+url
? printurl
? #抓取子鏈接代碼
? r = requests.get(url)
? #編碼轉(zhuǎn)換,不轉(zhuǎn)會(huì)報(bào)錯(cuò),可以在此轉(zhuǎn)尼变,也可以用u'字符串'的形式轉(zhuǎn)
? reload(sys)
? sys.setdefaultencoding('utf-8')
? #將html代碼寫入變量
? thisdata = r.text
? #將變量寫入文件
? f.write(thisdata)
? #關(guān)閉文件
? f.close()
? #print thisdata
測試時(shí)請(qǐng)注意縮進(jìn)贪庙。