requests+re爬取猫眼电影排行

import re

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

def get_one_page(url):
	#获取网页信息
    try:
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'}
        response = requests.get(url,headers=headers)
        if response.status_code==200:
            print(response.text)
            return response.text
        else:
            return None
    except RequestException:
        return None

def parse_one_page(html):
    #正则解析
    pattern = re.compile(
        '<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?title="(.*?)".*?star.*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>',
        re.S)
    #print(pattern)
    items = re.findall(pattern, html)

    for item in items:
        yield {  #yield 生成器
            'index': item[0],
            'image': item[1],
            'title': item[2],
            'actor': item[3].strip()[3:] if len(item[3]) > 3 else '',
            # strip()方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
            'time': item[4].strip()[5:] if len(item[4]) > 5 else '',
            'score': item[5] + item[6]
        }


def write_to_file_txt(conent):
	#写入文件
    #a:追加方式写入,如果该文件存在,则文件指针放在文件结尾,也就是说,会写在已经存在的内容后面。如果不存在,则创建。
    #w:已写入方式打开一个文件,如果该文件存在,则覆盖,不存在则创建新文件。
    with open('maoyan.txt','a',encoding='utf-8') as f:
        #print(type(json.dump(conent)))
        f.write(json.dumps(conent,ensure_ascii=False)+'\n')

def write_to_file_json(conent):
	#写入文件
    with open('maoyan.json','a',encoding='utf-8') as f:
        #print(type(json.dump(conent)))
        #ensure_ascii=False设置可以输出中文
        f.write(json.dumps(conent,indent=2,ensure_ascii=False))


def main(offset):
	#每一页都是有规律的变化,都是offset的值在改变
    url = 'https://maoyan.com/board/4?offset='+str(offset)
    print(url)
    html=get_one_page(url)
    #print(html)
    #print('------------------------------')
    items = parse_one_page(html)
    for item in items:
        print(item)
        print('------------')
        write_to_file_txt(item)
        write_to_file_json(item)


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


会遇到反爬:有可能只能爬前两页的内容。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值