python爬虫抓取猫眼电影排行

python爬虫抓取猫眼电影排行

#encoding=utf8
import json
import requests
from requests.exceptions import RequestException
import re
import time


def get_one_page(url):
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36'
        }
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None


def parse_one_page(html):
    pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a'
                         + '.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>'
                         + '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
    items = re.findall(pattern, html)
    for item in items:
        yield {
            'index': item[0],
            'image': item[1],
            'title': item[2],
            'actor': item[3].strip()[3:],
            'time': item[4].strip()[5:],
            'score': item[5] + item[6]
        }


def write_to_file(content):
    with open('result.txt', 'a', encoding='utf-8') as f:
        f.write(json.dumps(content, ensure_ascii=False) + '\n')


def main(offset):
    url = 'http://maoyan.com/board/4?offset=' + str(offset)
    html = get_one_page(url)
    for item in parse_one_page(html):
        print(item)
        write_to_file(item)


if __name__ == '__main__':
    for i in range(10):
        main(offset=i * 10)
        time.sleep(1)

 

爬虫入门分三步走:

1.获取url返回的html

def get_one_page(url):     参数url

在try-except中,构建headers后,调用requests的get方法,传入url和headers。返回一个response对象,判断返回的code是否为200,成功后返回response.text

2.解析html:

match函数:传入一个正则字符串和待匹配content,返回一个SRE_Match对象。该对象有两个方法group()和span(),group()取得匹配的字符串,按0序。span()获取匹配的长度。(该方法从头开始匹配,一旦开头不匹配,整个匹配就失败了)。

search()函数有效的解决了match()函数的局限,在整个待匹配的字符串中去匹配符合的第一段字符串。后续不再匹配。

findall()方法解决了search()只能匹配第一处的问题。

sub()函数用于修改文本。sub(正则取出将被替换的内容,取代的内容,字符串)如要删除,则取代的内容为''。

compile函数:将正则字符串编译成Pattern对象

3.写入文件(略)

 

posted @ 2018-12-12 09:57  慕云深  阅读(218)  评论(0)    收藏  举报