方法一、寫入進(jìn)Excel中
import requests,random,bs4,openpyxl
headers={'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
wb = openpyxl.Workbook() #創(chuàng)建工作薄
sheet = wb.active #獲取工作薄的活動表
sheet.title = 'douban' #工作表重命名
sheet['A1'] ='rank' #加表頭域蜗,給A1單元格賦值
sheet['B1'] ='name' #加表頭巨双,給B1單元格賦值
sheet['C1'] ='comment' #加表頭噪猾,給C1單元格賦值
sheet['D1'] ='link' #加表頭,給D1單元格賦值
for x in range(10): #以下與下方代碼一致
url = 'https://movie.douban.com/top250?start=' + str(x*25) + '&filter='
res = requests.get(url, headers=headers)
bs = bs4.BeautifulSoup(res.text,'html.parser')
bs = bs.find('ol',class_='grid_view')
for titles in bs.find_all('li'):
num = titles.find('em',class_='').text
title = titles.find('span',class_='title').text
comment = titles.find('span',class_='rating_num').text
url_movie = titles.find('a')['href']
sheet.append([num,title,comment,url_movie])
if titles.find('span',class_="inq") != None:
tes = titles.find('span',class_="inq").text
print(num + '.' + title + '——' + comment + '\n' + '推薦語:' + tes +'\n' + url_movie)
else:
print(num + '.' + title + '——' + comment + '\n' +'\n' + url_movie)
wb.save('douban.xlsx')
方法二筑累、存為.csv格式
import requests, random, bs4,csv
headers={'user-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
csv_file = open('movieTop250.csv','w',newline = '') #打開csv文件袱蜡,newline的意義在于排版正確
writer = csv.writer(csv_file) #創(chuàng)建一個writer對象
writer.writerow(['排名','電影','推薦語','電影鏈接']) #在csv文件里寫第一行
for x in range(10): #循環(huán)10頁
url = 'https://movie.douban.com/top250?start=' + str(x*25) + '&filter='
res = requests.get(url, headers=headers) #獲取網(wǎng)址
bs = bs4.BeautifulSoup(res.text, 'html.parser') #用BeautifulSoup解析網(wǎng)址內(nèi)容
bs = bs.find('ol', class_="grid_view") #利用find找到 標(biāo)簽為‘ol’,屬性為grid_view的內(nèi)容
for titles in bs.find_all('li'): #循環(huán)每個‘li’標(biāo)簽下的內(nèi)容
num = titles.find('em',class_="").text #直接用text方法取出文本
title = titles.find('span', class_="title").text
comment = titles.find('span',class_="rating_num").text
url_movie = titles.find('a')['href'] #所要提取的鏈接是‘href’的鍵
writer.writerow([num,title,comment,url_movie]) #循環(huán)每行寫num,title,comment,url_movie
if titles.find('span',class_="inq") != None: #需要判斷慢宗,因為有的推薦語為空
tes = titles.find('span',class_="inq").text
print(num + '.' + title + '——' + comment + '\n' + '推薦語:' + tes +'\n' + url_movie)
else:#推薦語為空時不顯示
print(num + '.' + title + '——' + comment + '\n' +'\n' + url_movie)
csv_file.close() #一定要記得關(guān)閉
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者