爬取排名前100的电影信息

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
        return None
    except RequestException:
        return None

def parse_one_page(text):
    soup = BeautifulSoup(text, 'lxml') #使用lxml XML 解析库
    #CSS选择器
    #div p 选择div节点内部的所有p节点
    #div>p 选择父节点为div节点的所有p节点
    #调用select()方法,传入相应的CSS选择器
    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.select('#app > div > div > div.main > dl > dd > div > div > div.movie-item-info > p.star')
    #find_all()查询所有符合条件的元素
    star = soup.find_all(name='p', class_='star') #class是关键字,所以加下划线
    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, #亦可用get_text()
                '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)
from requests.exceptions import RequestException
from urllib.parse import urlencode
from bs4 import BeautifulSoup
import requests
import json
import re
import time

#打开网页
def open_url(url):
    try:
        headers ={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36'}
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None
#解析每一页
def parse_page(html):
    soup = BeautifulSoup(html, 'lxml')
    items = soup.select('dd')
    for item in items:
        index = item.find(name='i', class_='board-index').get_text()
        name = item.find(name='p', class_='name').get_text()
        start = item.find(name='p', class_='star').get_text().strip()
        time = item.find(name='p', class_='releasetime').string
        score = item.find(name='p', class_='score').get_text()
        yield {
            'index':index,
            'name':name,
            'star':start,
            'time':time,
            'score':score
        }
#保存
def save(item):
    with open('maoyan.txt', 'a', encoding='utf-8') as f:
        f.write(json.dumps(item, ensure_ascii=False) + '\n')
#执行
if __name__ == '__main__':
    for i in range(10):
        base_url = 'http://maoyan.com/board/4?'
        params = {'offset': i*10}
        url = base_url + urlencode(params)
        html = open_url(url)
        for item in parse_page(html):
            print(item)
            save(item)
        time.sleep(2)

你可能感兴趣的:(爬虫)