爬取猫眼电影top100的代码

废话不说,代码附上:

 

#encoding:utf-8
import requests

import re

import json

from multiprocessing import Pool #多线程模块

 

#获取网页源代码

def get_one_page(url):

    #添加头信息

    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.3964.2 Safari/537.36'}

    html = requests.get(url,headers = headers)

    if html.status_code == 200:

        return html.text

    return None

 

#根据正则表达式提取信息

def parse_one_page(html):

    pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?title="(.*?)".*?data-src="(.*?)".*?star">(.*?)</p>.*?'

                         + 'releasetime">(.*?)</p>.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>',re.S)

    data = pattern.findall(str(html))

    for item in data:

        yield{

            'top':item[0],

            'name':item[1],

            'image_src':item[2],

            'actor':item[3].strip()[3:],

            'releasetime':item[4].strip()[5:],

            'score':item[5] + item[6]

        }

#将提取得数据写人文件

def write_of_file(content):

    # 'a'保留原先的内容,在尾部写入,因为用的是for循环写入,如果用'w'写入只会保留最后一组的数据,或者早打开文件,写入完在关闭,encoding='utf-8'以utf-8编码

    with open('result.txt','a',encoding='utf-8') as f:

        #ensure_ascii = False使中文正常输出

        f.write(json.dumps(content,ensure_ascii = False) + '\n')

        f.close()

#主函数

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_of_file(item)

 

if __name__ == '__main__':

    #定义多线程

    pool = Pool()

    pool.map(main,[i*10 for i in range(10)])

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

black-hole6

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值