爬蟲請求2 (2)

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import requests
import os

# 若是url中的參數包含中文,那麼須要先編碼,不然對方服務器不識別
# 參數是中文的必須編碼,requests包會自動編碼

city = input("請輸入城市名稱:")
url = "http://api.map.baidu.com/telematics/v3/movie?qt=hot_movie&location=%E9%83%91%E5%B7%9E%E5%B8%82&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&output=json"
response = requests.get(
    url,
    params={"location":city}
)
# response.json() 自動將響應數據解析爲json對象
# 注意:數據格式必須知足json
print(type(response.json()))
# 也能夠經過導入json包手動轉換
# 導入文件通常寫在文件的最上面
import json
json_obj = json.loads(response.text)
print(type(response.text))
json_obj = response.json()
movie_list = json_obj.get("result").get("movie")
with open("movie_info.html","w",encoding="utf-8") as f:
    f.write("""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>電影信息網</title>
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.css">
</head>
<body>
    <div class="container">
        <table class="table table-bordered table-hover table-responsive">
            <tr>
                <td>ID</td>
                <td>電影圖片</td>
                <td>電影名稱</td>
                <td>電影評分</td>
                <td>上映時間</td>
                <td>電影分類</td>
                <td>演員表</td>
            </tr>""")
    for idx, movie in enumerate(movie_list):
        # 電影圖片,電影名稱,評分,上映時間,分類,演員
        '''
        電影圖片,電影名稱,評分,上映時間,分類,演員
        '''
        # python中註釋只有#一種形式,三個單引號和三個雙引號表示字符串,不叫註釋
        movie_picture = movie.get("movie_picture")
        movie_picture_response = requests.get(movie_picture)
        img_response = requests.get(movie_picture)
        movie_name = movie.get("movie_name")

        if not os.path.exists("imgs"):
            os.makedirs("imgs")
        with open("imgs/"+movie_name+".jpg","wb") as f1:
            f1.write(movie_picture_response.content)
        movie_score = movie.get("movie_score")
        movie_release_date = movie.get("movie_release_date")
        movie_tags = movie.get("movie_tags")
        movie_starring = movie.get("movie_starring")
        f.write("""<tr>
                <td>%s</td>
                <td><img src="%s" alt="蜘蛛俠" width="50px"></td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
                <td>%s</td>
            </tr>""" % (idx+1, "imgs/"+movie_name+".jpg", movie_name, movie_score, movie_release_date, movie_tags, movie_starring[:10]+"..."))
        print(movie_picture, movie_name, movie_score, movie_release_date, movie_tags, movie_starring)
    f.write("""</table></div></body></html>""")
相關文章
相關標籤/搜索