用Requests+正则表达式爬取猫眼电影

作者: 1想得美 | 来源:发表于2017-08-14 20:40 被阅读260次

一、介绍

最近在看崔庆才老师的视频,崔大大确实不错,思路和代码书写都很谨慎,我就再码码字吧,方便以后查阅或温习

二、流程

  • 用浏览器打开猫眼电影,分析站点

  • 抓取单页内容
    利用Requests请求目标站点,得到单个网页HTML代码,返回结果

  • 正则表达式分析
    根据HTML代码分析得到的名称、主演、上映时间、评分、图片链接等信息

  • 保存至文件
    通过文件的形式将结果保存,每一部电影一个结果一行Json字符串

  • 开启循环及多线程
    对多页内容遍历,开启多线程提高抓取速度

三、代码

import requests
from requests.exceptions import RequestException
import re
import json

from multiprocessing import Pool  #多线程

def get_one_page(url):
    try:
        response=requests.get(url)
        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)
    #print(items)
    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.text','a',encoding='utf-8') as f:
        f.write(json.dumps(content,ensure_ascii=False)+'\n')
        f.close()

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

if __name__=='__main__':   
    #main()
    for i in range(10):
        main(i*10)
    '''pool=Pool()
    pool.map(main,[i*10 for i in range(10)])        多线程'''

四、最后得到的text文件

1502715300(1).png

相关文章

网友评论

  • TinXie:好複雜...
    學習中...
  • 七月宋:好像是多进程,引入进程池吧
  • Mo丶染洛凉:加油
    1想得美:@Mo丶染洛凉 嗯嗯,现在跟着崔老师的视频爬,赶脚爬虫需要的网页知识还是挺多的

本文标题:用Requests+正则表达式爬取猫眼电影

本文链接:https://www.haomeiwen.com/subject/shrprxtx.html