300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 爬取豆瓣最受欢迎的250部电影慢慢看

爬取豆瓣最受欢迎的250部电影慢慢看

时间:2021-05-11 14:20:14

相关推荐

爬取豆瓣最受欢迎的250部电影慢慢看

接下来咱们就来爬取豆瓣上评分最高的

250部电影

这次我们就要来使用上次说的

BeautifulSoup+Reuqests

进行爬取啦

这次

我们将爬取到的内容存放到 excel 吧

首先打开我们的目标链接

/top250

可以看到这样一个网页

每一页显示了 25 条数据

当我们点击下一页的时候

链接请求参数变了

/top250?start=25&filter=

我们一眼就看的出来

这里就是从第 25 条数据开始加载的

所以

我们可以使用这个start=25来做变量

实现翻页获取信息

接下来我们来看下我们要的主要信息

电影名称

电影图片

电影排名

电影评分

电影作者

电影简介

首先请求豆瓣网

def main(page):url = '/top250?start='+ str(page*25)+'&filter='html = request_douban(url)soup = BeautifulSoup(html)

def request_douban(url):try:response = requests.get(url)if response.status_code == 200:return response.textexcept requests.RequestException:return None

然后根据服务器返回的请求响应,对其进行解析

def save_to_excel(soup):for item in list:item_name = item.find(class_='title').stringitem_img = item.find('a').find('img').get('src')item_index = item.find('em').stringitem_score = item.find(class_='rating_num').stringitem_author = item.find('p').stringitem_intr = item.find(class_='inq').stringprint('爬取电影:' + item_index + ' | ' + item.name + ' | ' + item_score + ' | ' + item_intr)

整体代码如下:

#BeautifulSoup练习from bs4 import BeautifulSoupimport requests, sysimport xlwtimport lxmldef request_douban(url):try:response = requests.get(url)if response.status_code == 200:return response.textexcept requests.RequestException:return Nonedef save_to_excel(soup):book = xlwt.Workbook(encoding='utf-8',style_compression=0)list = soup.find(class_='grid_view').find_all('li')sheet = book.add_sheet('豆瓣电影Top250', cell_overwrite_ok=True)sheet.write(0, 0, '名称')sheet.write(0, 1, '图片')sheet.write(0, 2, '排名')sheet.write(0, 3, '评分')sheet.write(0, 4, '作者')sheet.write(0, 5, '简介')n = 1for item in list:item_name = item.find(class_='title').stringitem_img = item.find('a').find('img').get('src')item_index = item.find('em').stringitem_score = item.find(class_='rating_num').stringitem_author = item.find('p').textitem_intr = item.find(class_='inq').stringprint('爬取电影:' + item_index + ' | ' + item_name + ' | ' +item_author+' | ' + item_score + ' | ' + item_intr)sheet.write(n, 0, item_name)sheet.write(n, 1, item_img)sheet.write(n, 2, item_index)sheet.write(n, 3, item_score)sheet.write(n, 4, item_author)sheet.write(n, 5, item_intr)n = n+1print("n:"+str(n))book.save('豆瓣最受欢迎的250部电影.xlsx')def main(page):url = '/top250?start='+ str(page*25)+'&filter='html = request_douban(url)soup = BeautifulSoup(html)save_to_excel(soup)# list = soup.find(class_='grid_view').find_all('li')if __name__ == '__main__':main(0)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。