# -*- coding: utf-8 -*-
"""
豆瓣最新上映电影爬取
# ul = etree.tostring(ul, encoding="utf-8").decode("utf-8")
"""
import requests
from lxml import etree
#1.抓取目标网站页面
def getHtml(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
'Referer': 'https://movie.douban.com/',
'Accept': 'application/json, text/javascript, */*; q=0.01'
}
resp = requests.get(url, headers=headers)
# print(resp.text)#返回的是经过解码后的字符串,是str(unicode)类型,有时候会出现解码为乱码的情况,这时就需要自己指定解码方式
# print(resp.content)#返回的是一个原生的字符串,就是从网页上抓取的没有经过处理的字符串,是bytes类型
text = resp.text
return text
#2.将抓取的网页根据一定规则进行提取
def extractData(text):
html = etree.HTML(text)
#1拿到第一个class='lists'的ul元素
ul = html.xpath("//ul[@class='lists']")[0]
#2获取每一部电影的信息,ul标签下的所有li标签
lis = ul.xpath("./li")
movies = []#用于存放所有电影的列表
for li in lis:
#获取li的data-title属性
title = li.xpath("@data-title")[0]#电影名称
score = li.xpath("@data-score")[0]#评分
duration = li.xpath("@data-duration")[0]#持续时间
director = li.xpath("@data-director")[0]#导演
actors = li.xpath("@data-actors")[0]#演员
thumnail = li.xpath(".//img/@src")[0]#.代表当前标签,拿到所有电影的缩略图
# 构造成字典
movie = {
'title': title, 'score': score,
'duration': duration, 'director': director,
'actors': actors, 'thumnail': thumnail
}
movies.append(movie)
return movies
if __name__ == "__main__":
url = "https://movie.douban.com/cinema/nowplaying/beijing/"
text = getHtml(url)
print(extractData(text))