使用Beautiful Soup爬取猫眼TOP100的电影信息

  使用Beautiful Soup爬取猫眼TOP100的电影信息,将排名、图片、电影名称、演员、时间、评分等信息,提取的结果以文件形式保存下来。

import time
import json
import requests
from bs4 import BeautifulSoup


def get_one_page(url):
    try:
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}
        response = requests.get(url, headers=headers)
        response.encoding = response.apparent_encoding
        if response.status_code == 200:
            return response.text
        else:
            return None
        return None
    except RequestException:
        return None

def parse_one_page(text):
    soup = BeautifulSoup(text, 'lxml')
    ranking = soup.select('dd .board-index')
    imgsrc = soup.select('#app > div > div > div.main > dl > dd > a > img.board-img')
    title = soup.select('#app > div > div > div.main > dl > dd > a')
    star = soup.find_all(name='p', class_='star')
    #star = soup.select('#app > div > div > div.main > dl > dd > div > div > div.movie-item-info > p.star')
    releasetime = soup.find_all(name='p', class_='releasetime')
    interger = soup.find_all(name='i', class_='integer')
    fraction = soup.find_all(name='i', class_='fraction')
    for i in range(10):
        yield {
                'index': ranking[i].string,
                'image': imgsrc[i].attrs['data-src'],
                'title': title[i]['title'],
                'actor': star[i].string.strip()[3:],
                'time': releasetime[i].string.strip()[5:],
                'score': interger[i].string + fraction[i].string

            }
       
def write_to_file(content):
    with open('maoyan.txt', 'a', encoding='utf-8') as f:
        f.write(json.dumps(content, ensure_ascii=False)+'\n')
        
        
def main(offset):
    url = 'https://maoyan.com/board/4?offset=' + str(offset)
    text = get_one_page(url)
    for item in parse_one_page(text):
        print(item)
        write_to_file(item)
        
    
if __name__ == '__main__':
    for i in range(10):
        main(offset=i*10)
        time.sleep(1)

 

上一篇:爬取百度热搜榜


下一篇:Bmob Unity Android支付接入文档