前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >正则爬取猫眼电影

正则爬取猫眼电影

作者头像
听城
发布2018-08-30 11:10:19
4540
发布2018-08-30 11:10:19
举报
文章被收录于专栏:杂七杂八杂七杂八

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

主要内容

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

设置headers

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

代码语言:javascript
复制
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)的调用方式。

代码语言:javascript
复制
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保存

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

多线程抓取

代码语言:javascript
复制
from multiprocessing import Pool
pool = Pool()
pool.map(main,[i*10 for i in range(10)])

全部代码

代码语言:javascript
复制
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)])
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.08.18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 主要内容
  • 设置headers
  • 爬取内容
  • 结果json保存
  • 多线程抓取
  • 全部代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档