1. 程式人生 > >爬取豆瓣正在上映的影片資訊

爬取豆瓣正在上映的影片資訊

import requests
from lxml import etree


# 將目標網站上的頁面抓取下來
# headers  ->   url  -> requests   -> response
# response.text  返回的是一個經過解碼後的字串,是str(unicode)型別
# response.content 返回的是一個原生的字串,就是從網頁上抓取下來的,沒有經過處理的字串,是bytes型別
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
    'Referer':'https://movie.douban.com/'
}

url = 'https://movie.douban.com/cinema/nowplaying/nanjing/'
response = requests.get(url,headers=headers)
text = response.text

# 將抓取下來的資料根據一定的規則進行提取
html = etree.HTML(text,parser=etree.HTMLParser())    # parser   html解析器
ul = html.xpath("//ul[@class='lists']")[0]    # 獲取屬性為lists的ul標籤內容,因為正在上映和即將上映是一樣的,所以取列表的第一個元素,即正在上映的ul
lis = ul.xpath("./li")    # 獲取ul標籤下的li標籤(每部影片在一個li標籤下面)
movies = []

for li in lis:
    title = li.xpath("@data-title")[0]   # xpath返回的是一個列表    影片名字
    score = li.xpath("@data-score")[0]   # 影片評分
    release_time = li.xpath("@data-release")[0]  # 上映時間
    time = li.xpath("@data-duration")[0]    # 影片時長
    region = li.xpath("@data-region")[0]   # 製片國家地區
    director = li.xpath("@data-director")[0]  #導演
    actors = li.xpath("@data-actors")[0]   #主演
    category = li.xpath("@data-category")[0]    #上映型別
    image = li.xpath(".//img/@src")[0]   # 圖片連結


    movie = {
        'title':title,
        'score':score,
        'release':release_time,
        'time':time,
        'region':region,
        'director':director,
        'actors':actors,
        'category':category,
        'image_link':image
    }

    movies.append(movie)

for movie in movies:
    for value in movie.values():
        print(value + "||",end="")
    print()