python 爬取猫眼前一百个电影

学习自《python3网络爬虫开发实战》, 整理以备日后回顾

网上其实很多猫眼电影的爬取实例,然而找了好久都没找到xpath解析的相关程序,再加上网页自身也多少存在变化,
所以就一时兴起自己写一个简单程序试了一下

import requests
from lxml import etree
import time
from requests.exceptions import RequestException

def get_page(page):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 '
                          '(KHTML, like Gecko) Chrome/38.0.2125.122 UBrowser/4.0.3214.0 Safari/537.36'
        }
        url = 'https://maoyan.com/films?showType=3&offset=' + str(page)
        response = requests.get(url, headers=headers).text
        html = etree.HTML(response, parser=etree.HTMLParser())
        return html
    except RequestException :
        return None

def number_title(number):
    return number+1

def parse_page(html):
    titles = html.xpath('//a[@data-act="movies-click" and @target="_blank"]/text()')
    number = 0
    for title in titles:
        number = number_title(number)
        print(str(number) + ' ' + title)

def main():
    for page in range(0,4):
        page = page * 30
        print('第' + str(int((page)/30+1)) + '页正在打印')
        time.sleep(1)
        parse_page(get_page(page))

if __name__ == '__main__':
    main()

成文时每页是有三十个电影的,所以就直接弄了一百二十个电影,标号是每页的标号,1 到 30 ,结果也并未保存,只是单纯
输出看了一下 ,也许过段时间页面存在变化的话还会再改

你可能感兴趣的:(爬虫)