python爬蟲 爬取豆瓣電影 1-10 ajax 資料

donghongchao發表於2024-07-04
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
    }

    data = urllib.parse.urlencode(data)
    url = base_url + data
    print(url)
    headers = {
        'User-Agent': ' Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 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 fd:
        fd.write(content)


# 程式入口
if __name__ == '__main__':
    start_page = int(input("請輸入起始的頁碼"))
    end_page = int(input("請輸入結束的頁碼"))

    for page in range(start_page, end_page + 1):
        request = create_request(page)
        # 獲取響應資料
        content = get_content(request)
        # 下載
        down_load(page, content)

相關文章