爬取电影天堂

爬取每部电影的详细信息

分析每页的url,可以得到规律是:第t页的url为: http://dytt8.net/html/gndy/dyzz/list_23_t.html
于是可以先分析第一页,然后对页数进循环,就可得到所有最新电影的详细信息。

from lxml import etree
headers={
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36"
}
def get_movie_url(url):
    resp=requests.get(url,headers=headers)
    text=resp.text
    html=etree.HTML(text)
    movie_urls = html.xpath("//td//a[@class='ulink']/@href")
    #定位到所有的td下class='ulink'的a标签取出href属性的值,返回的就是每个电影详情页的url
    return movie_urls
#得到详情页的url之后,对详情页进行分析。
def parse_detail_pages(url):
	resp = requests.get(url, headers=headers)
    text = resp.content.decode("gbk")#详情页采取的gbk的编码方式
    html = etree.HTML(text)
    Zoom = html.xpath("//div[@id='Zoom']")[0]
    #得到Zoom中所有的文本信息
    infos = Zoom.xpath("//text()")
    movie={}
    #对infos列表进行循环,利用enumerate() 函数同时列出数据和数据下标
    #startswith() 方法用于检查字符串是否是以指定子字符串开头,是返回 True,否则返回False
    #strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列,str.strip()
    去除首尾空格。该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
    for index,info in enumerate(infos): 
        if info.startswith("◎片  名"):
            name= info.replace("◎片  名", "").strip()
            movie["名称"]=name
        elif info.startswith("◎年  代"):
            time= info.replace("◎年  代", "").strip()
            movie["上映时间"] = time
        elif info.startswith("◎产  地"):
            country = info.replace("◎产  地", "").strip()
        elif info.startswith("◎类  别"):
            class_name = info.replace("◎类  别", "").strip()
            movie["类别"] = class_name
        elif info.startswith("◎字  幕"):
            language = info.replace("◎字  幕", "").strip()
            movie["语言"] = language
        elif info.startswith("◎主  演"):
            actor = info.replace("◎主  演", "").strip()
            actors = [actor]
            for x in range(index+1,len(infos)):
                actor=infos[x].strip()
                if actor.startswith("◎"):
                    break
                actors.append(actor)
            movie["主演"]=actors
        elif info.startswith("◎简  介")
            intro=infos[index+1].strip()
            movie["简介"] = intro
    downloadurl=html.xpath("//font[@color='red']/a/@href")
    movie["下载地址"]=downloadurl
    return movie

def get_movie_url(url):
    resp=requests.get(url,headers=headers)
    text=resp.text#如果出现乱码的情况,可以写成text= resp.content.decode('utf-8')
    html=etree.HTML(text)
    urls = html.xpath("//td//a[@class='ulink']/@href")
    return urls
def spider():
    #得到页数的url
    for i in range(1, 8):
        url = "http://dytt8.net/html/gndy/dyzz/list_23_{}.html"
        com_page_url = url.format(i)
        urls=get_movie_url(com_page_url)
        #得到每个电影详细介绍的url
        print("*"*20,i,1)
        for url in urls:
            com_url = "http://dytt8.net/" + url
            movie=parse_detail_page(com_url)
            print(movie)
spider()
	
	

你可能感兴趣的:(爬取电影天堂)