Python爬取猫眼电影排行TOP100的电影

 打开目标站点,查看榜单信息,如图: 1排名第一的电影是霸王别姬,页面中显示的有效信息有影片名称、主演、上映时间、上映地区、评分、图片等信息。
  翻页规律:按住鼠标滑轮滚动到页面底部,点击下一页,观察页面URL和内容发生的变化,如图: 2可以发现页面的URL变成http://maoyan.com/board/4?offset=10, 比之前的URL多了一个参数,那就是offset=10,而目前显示的结果是排行11-20名的电影,初步推断这是一个偏移量的参数。再点击下一页,发现页面的URL变成了http://maoyan.com/board/4?offset=20, 参数offset变成了20,而显示的结果是排行21~30的电影
  由此可以总结出规律,off代表偏移量值,如果偏移量为n,则显示的电影序号就是n+1到n+10,每页显示10个。所以,如果想获取TOP100电影,只需要分开请求10次,而10次的offset参数分别设置为0、10、20、…90即可,这样获取不同的页面之后,再用正则表达式提取出相关信息,就可以得到TOP100的所有电影信息了。

import requests
import re
import json
from requests.exceptions import RequestException
from pymongo import MongoClient
import time
'''
想要学习Python?Python学习交流群:984632579满足你的需求,资料都已经上传群文件,可以自行下载!
'''
# 创建数据库连接
client = MongoClient('mongodb://localhost:27017/')
db = client.maoyan
collection = db.rank

def get_one_page(url):
    """
    获取每页的网页源代码
    :param url: 请求链接
    :return: 网页的文本内容
    """
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
        }
        response = requests.get(url=url, headers=headers)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None

def parse_one_page(html):
    """
    使用正则表达式解析网页数据
    :param html: 网页的文本内容
    :return: 字典
    """
    pattern = re.compile(
        r'<dd>.*?board-index.*?>(.*?)</i>.*?data-src="(.*?)".*?name.*?a.*?>(.*?)</a>.*?star.*?>(.*?)</p>.'
        r'*?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].split('@')[0],
            'title': item[2].strip(),
            'actor': item[3].strip()[3:] if len(item[3]) > 3 else '',
            'time': item[4].strip()[5:] if len(item[4]) > 5 else '',
            'score': item[5].strip() + item[6].strip()
        }

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_to_mongo(item):
    """
    将数据存储到MongoDB
    :param dict: 字典类型的数据
    :return: None
    """
    collection.insert(item)

def main(offset):
    url = 'http://maoyan.com/board/4?offset={}'.format(str(offset))
    html = get_one_page(url)
    for item in parse_one_page(html):
        write_to_file(item)
        save_to_mongo(item)

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

### 抓取猫眼电影Top100数据并存入数据库 为了实现这一目标,可以采用`requests`库来获取网页内容,并利用正则表达式或BeautifulSoup解析HTML文档中的所需信息。考虑到猫眼网站可能存在反爬措施,适当引入`selenium`模拟真实浏览器行为有助于绕过某些验证机制[^2]。 #### 准备工作 安装必要的Python包: ```bash pip install requests beautifulsoup4 pymysql selenium ``` 启动Selenium WebDriver(假设使用ChromeDriver),这一步骤对于处理动态加载的内容至关重要[^5]。 #### 获取页面源码 通过设置请求头模仿正常访问者的行为模式,同时加入Cookies以应对可能存在的登录状态校验或其他形式的身份识别。 ```python from selenium import webdriver import time options = webdriver.ChromeOptions() driver = webdriver.Chrome(options=options) url = "https://maoyan.com/board/4" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', } cookies_str = '_lxsdk_cuid=xxx;' # 替换为实际获得的有效cookie字符串 driver.get(url) time.sleep(3) # 等待页面完全渲染 for cookie in cookies_str.split(';'): name, value = cookie.strip().split('=', 1) driver.add_cookie({'name': name, 'value': value}) driver.refresh() # 刷新使新添加的cookie生效 html_content = driver.page_source ``` #### 解析与提取数据 运用BeautifulSoup简化DOM树结构遍历操作,定位到包含排名、图片链接、片名、演员阵容、发布日期及评分的具体标签位置[^1]。 ```python from bs4 import BeautifulSoup soup = BeautifulSoup(html_content, 'html.parser') films = [] items = soup.find_all('dd')[:100] for item in items: rank = int(item.select_one('.board-index').text) poster_url = item.img['data-src'] title = item.a.text.strip() actors = item.select_one('.star').text.replace('\n', '').strip()[3:] release_time = item.select_one('.releasetime').text[5:] score = float(item.select_one('.integer').text[:-1]) + \ float(item.select_one('.fraction').text)/10 films.append({ 'rank': rank, 'poster_url': poster_url, 'title': title, 'actors': actors, 'release_time': release_time, 'score': score }) ``` #### 数据入库 建立MySQL连接并将每部电影的信息作为记录写入表内;这里假定已创建好名为`film_top_100`的目标表格[^3]。 ```sql CREATE TABLE IF NOT EXISTS `film_top_100` ( id INT AUTO_INCREMENT PRIMARY KEY, rank INT NOT NULL, poster_url VARCHAR(255), title TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci, actors TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci, release_time DATE, score DECIMAL(3, 1) ); ``` 执行批量插入语句前先关闭自动提交功能以便提高效率,在遇到错误时也能方便回滚事务保护已有数据完整性。 ```python import pymysql.cursors connection = pymysql.connect( host='localhost', user='root', password='password', database='movies_db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) try: with connection.cursor() as cursor: sql = """ INSERT INTO film_top_100(rank, poster_url, title, actors, release_time, score) VALUES (%s, %s, %s, %s, STR_TO_DATE(%s,'%Y-%m-%d'), %s) """ for film in films: try: cursor.execute(sql, tuple(film.values())) except Exception as e: print(e) connection.commit() finally: connection.close() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值