前提:
第一页url
https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&start=0&limit=20
第二页url
https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&start=20&limit=20
第三页url
https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&start=40&limit=20
观察得出每页的url中得start发生了变化
(一)获取的页数
start_page = int(input("请输入起始的页码:"))
end_page = int(input("请输入结束的页码:"))
for page in range(start_page, end_page + 1):
print(page)
- python基础知道range()左闭右开
(二)每一页的请求对象的定制
def create_request(page):
base_url = ("https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&")
data = {
'start': (page - 1) * 20,
'limit': 20
}
# start = 60 & limit = 20 获得&符号
data = urllib.parse.urlencode(data)
url = base_url + data
# print(url)
headers = {
"user-agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"
}
request = urllib.request.Request(url=url, headers=headers)
return request
需要拼接url
base_url = "https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&"
data = {
'start': (page - 1) * 20,
'limit': 20
}
# start = 60 & limit = 20 获得&符号
data = urllib.parse.urlencode(data)
url = base_url + data
(三)获得响应数据
def get_content(request):
response = urllib.request.urlopen(request)
content = response.read().decode("utf-8")
return content
(四) 下载数据
def down_load(page, content):
with open('douban' + str(page) + '.json', 'w', encoding="utf-8") as fp:
fp.write(content)
(五)完整代码
import urllib.parse
import urllib.request
# 每一页的请求对象的定制
def create_request(page):
base_url = ("https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&")
data = {
'start': (page - 1) * 20,
'limit': 20
}
# start = 60 & limit = 20 获得&符号
data = urllib.parse.urlencode(data)
url = base_url + data
# print(url)
headers = {
"user-agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36"
}
request = urllib.request.Request(url=url, headers=headers)
return request
# 获得响应数据
def get_content(request):
response = urllib.request.urlopen(request)
content = response.read().decode("utf-8")
return content
# 下载数据
def down_load(page, content):
with open('douban' + str(page) + '.json', 'w', encoding="utf-8") as fp:
fp.write(content)
if __name__ == '__main__':
start_page = int(input("请输入起始的页码:"))
end_page = int(input("请输入结束的页码:"))
for page in range(start_page, end_page + 1):
print(page)
# 每一页的请求对象的定制
request = create_request(page)
# 获得响应数据
content = get_content(request)
# 下载数据
down_load(page, content)
(六)结果
努力中。。。