更多技術文章請訪問我的個人博客
<div>
提取出來,代碼直接用urlopen弄了出來,我先保存到一個文件里,要慢慢的測試,直接用文件里的代碼就可以了,省得每次都抓取頁面。<div class="bd doulist-subject"></div>
效果如下圖
下面是全部的代碼,大家可以參考一下。
#!/usr/bin/env python# -*- coding=utf-8 -*-import sysreload(sys)sys.setdefaultencoding( "utf-8" )import urllib2import reimport timefrom bs4 import BeautifulSoupdef get_html(url): #通過url獲取網頁內容 result = urllib2.urlopen(url) return result.read() # save_file(result.read(), 'thefile.txt')def get_movie_all(html): #通過soup提取到每個電影的全部信息,以list返回 soup = BeautifulSoup(html) movie_list = soup.find_all('div', class_='bd doulist-subject') return movie_listdef get_movie_one(movie): result = [] # 用于存儲提取出來的電影信息 soup_all = BeautifulSoup(str(movie)) title = soup_all.find_all('div', class_='title') soup_title = BeautifulSoup(str(title[0])) for line in soup_title.stripped_strings: # 對獲取到的<a>里的內容進行提取 result.append(line) # num = soup_all.find_all('span', class_='rating_nums') num = soup_all.find_all('span') result.append(num[1].contents[0]) soup_num = BeautifulSoup(str(num[0])) for line in soup_num.stripped_strings: # 對獲取到的<span>里的內容進行提取 result = result + line info = soup_all.find_all('div', class_='abstract') soup_info = BeautifulSoup(str(info[0])) result_str = "" for line in soup_info.stripped_strings: # 對獲取到的<div>里的內容進行提取 result_str = result_str + line result.append(result_str) return result #返回獲取到的結果def save_file(text, filename): #保存網頁到文件 f= open(filename,'ab') f.write(text) f.close()def read_file(filename): #讀取文件 f = open(filename,'r') text = f.read() f.close() return textif __name__=='__main__': for i in range(0,426,25): url = 'https://www.douban.com/doulist/3516235/?start='+str(i)+'&sort=seq&sub_type=' html = get_html(url) movie_list = get_movie_all(html) for movie in movie_list: #將每一頁中的每個電影信息放入函數中提取 result = get_movie_one(movie) text = ''+'電影名:'+str(result[0])+' | 評分:'+str(result[1])+' | '+str(result[2])+'/n'+'/t' save_file(text,'thee.txt') time.sleep(5) #每隔5秒抓取一頁的信息更多技術文章請訪問我的個人博客
新聞熱點
疑難解答