学习到request模块,我们使用学到的技巧来抓取豆瓣电影的排行榜
1 分析接口
'https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=20&limit=20'
'https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=40&limit=20'
'https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=60&limit=20'
总结 通过观察 只有start的值不一样,所以我们可以在这里直接对字符串进行拼接
11&interval_id=100%3A90&action=&limit=20&start="+str((page-1)*20)
接下来直接上代码
import requests
for page in range(1,11,1):
url="https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&limit=20&start="+str((page-1)*20)
print('第%d页:%s'%(page,url))
response = requests.get(url)
print(response.json())
for movie in response.json():
title = movie['title']
with open('douban.txt','a',encoding='utf-8') as fp:
fp.write(title+'\n')
注意
在第一次写的时候我试图用%d的形式直接进行字符串的替换,结果失败了,原因:
上图标志的是红方框这里的%3A代表一个:号
在使用%d之后,这里不能识别%3的表示,导致失败