美文网首页
正则爬取猫眼电影

正则爬取猫眼电影

作者: 听城 | 来源:发表于2018-08-18 15:11 被阅读16次

这篇文章主要是利用requests来抓取猫眼电源Top100榜单

主要内容

  • requests设置headers,防止反爬
  • 爬取内容
  • 结果json保存
  • 多线程抓取

设置headers

设置headers的主要目的就是防止用户请求被请求页面判定为恶意请求,最基本的就是要让用户的请求模拟浏览器请求的方式。通常在headers设置user-agent来起到模拟浏览器的方式。

session = requests.Session()
headers = {
    'Connection': 'keep-alive',
    'Accept': 'text/html, */*; q=0.01',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36',
    'Accept-Encoding': 'gzip, deflate, sdch',
    'Accept-Language': 'zh-CN,zh;q=0.8,ja;q=0.6'
}

爬取内容

我们使用正则表达式方式来获取我们想要的数据。这里会用re.compile()函数,该函数根据包含的正则表达式的字符串创建模式对象。可以实现更有效率的匹配。在直接使用字符串表示的正则表达式进行search,match和findall操作时,python会将字符串转换为正则表达式对象。而使用compile完成一次转换之后,在每次使用模式的时候就不用重复转换。当然,使用re.compile()函数进行转换后,re.search(pattern, string)的调用方式就转换为 pattern.search(string)的调用方式。

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)

结果json保存

# ensure_ascii=False是为了中文正常显示
    with open('result.txt', 'a', encoding='utf-8') as f:
        f.write(json.dumps(content, ensure_ascii=False) + '\n')

多线程抓取

from multiprocessing import Pool
pool = Pool()
pool.map(main,[i*10 for i in range(10)])

全部代码

import re
import os
import json
import requests
from multiprocessing import Pool
from requests.exceptions import RequestException

session = requests.Session()
headers = {
    'Connection': 'keep-alive',
    'Accept': 'text/html, */*; q=0.01',
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36',
    'Accept-Encoding': 'gzip, deflate, sdch',
    'Accept-Language': 'zh-CN,zh;q=0.8,ja;q=0.6'
}


def get_one_page(url):
    try:
        response = session.get(url,headers=headers)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return 'RequestException'


def parse_one_page(html):
    print('parse page')
    #re.S是为了匹配换行符
    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 save_image_file(url, path):
    '''
    保存电影封面
    '''
    ir = requests.get(url)
    if ir.status_code == 200:
        with open(path, 'wb') as f:
            f.write(ir.content)
            f.close()

def main(offset):
    url = 'http://maoyan.com/board/4?offset=' + str(offset)
    html = get_one_page(url)
    # 封面文件夹不存在则创建
    if not os.path.exists('covers'):
        os.mkdir('covers')
    for item in parse_one_page(html):
        #print(item)
        write_to_file(item)
        save_image_file(item['image'], 'covers/' + '%03d' % int(item['index']) + item['title'] + '.jpg')


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

相关文章

网友评论

      本文标题:正则爬取猫眼电影

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