Python 2.7_Second_try_爬取陽光電影網_擷取電影下載地址並寫入檔案 20161207

來源:互聯網
上載者:User

標籤:decode   爬取   color   sources   port   get   str   技術   ref   

1、昨天文章http://www.cnblogs.com/Mr-Cxy/p/6139705.html 是擷取電影網站主菜單 然後擷取每個菜單下的電影url 

2、今天是對電影url 進行再次解析擷取 並寫入檔案  調用函數和類多線程還沒實現 一步步來吧

3、問題:我想實現的是先對菜單進行建立檔案目錄 然後每個目錄下以擷取的電影名稱.txt 作為檔案 檔案內是下載串連,但是建立一級菜單檔案夾沒問題 用OS模組就可以建立 在寫入電影名稱.txt時候出問題 報錯

我以為是編碼問題 f.open(目錄名+電影名.txt,"a") 前面是字元型也用到decode=‘utf-8‘ 轉換了 還是報錯

無奈我只好先以追加模式 寫入一個固定的文本txt檔案 明天再看看

 

4、python 代碼 

#coding:utf-8import requestsfrom bs4 import BeautifulSoup as bs#爬取入口rooturl="http://www.ygdy8.com/index.html"#擷取網頁源碼res=requests.get(rooturl)#網站編碼gb2312res.encoding=‘gb2312‘#網頁源碼html=res.textsoup=bs(html,‘html.parser‘)cate_urls = []for cateurl in soup.select(‘.contain ul li a‘):    #網站分類標題    cate_name=cateurl.text.encode(‘utf-8‘)    #分類url 進行再次爬取    cate_url="http://www.ygdy8.com/"+ cateurl[‘href‘]    cate_urls.append(cate_url)    print "網站一級菜單:",cate_name,"菜單網址:",cate_url    # newdir = "E:/moive24/"+ cate_name    # os.makedirs(newdir.decode("utf-8"))    # print "建立分類目錄成功------" + newdir#每個菜單url 解析for i in range(len(cate_urls)):    cate_listurl=cate_urls[i]    res = requests.get(cate_listurl)    res.encoding = ‘gb2312‘    html = res.text    soup = bs(html, ‘html.parser‘)    print "正在解析第"+str(i+1)+"個連結",cate_urls[i]    contenturls=[]    contents=soup.select(‘.co_content8 ul‘)[0].select(‘a‘)    #print contents    for title in contents:        moivetitle=title.text.encode(‘utf-8‘)        moiveurl="http://www.ygdy8.com/"+ title[‘href‘]        contenturls.append(moiveurl)        print moivetitle,moiveurl        # file_name=newdir +‘/‘+ moivetitle +‘.txt‘        # print file_name        # f = open(file_name.decode("utf-8"), "wb")        # f.close()        res = requests.get(moiveurl)        res.encoding = ‘gb2312‘        html = res.text        soup = bs(html, ‘html.parser‘)        moive_sources=soup.select(‘#Zoom span tbody tr td a‘)        for source in moive_sources:            moive_source=source[‘href‘]            #print moive_source            f=open(‘E:/moive24/moive.txt‘,‘a‘)            f.write(moive_source.encode("utf-8") + "\n")            f.close

  

Python 2.7_Second_try_爬取陽光電影網_擷取電影並寫入檔案 20161207

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.