[Python]爬取猫眼电影Top100榜

猫眼电影Top100爬虫实战
本文介绍了一次使用Python正则表达式抓取猫眼电影Top100榜单信息的实践过程,包括如何获取网页源码、解析数据并保存至本地文件等步骤。

        之前写爬虫用的都是BeautifulSoup库,这次学了一下正则表达式,用猫眼电影的Top100榜试了一下。



import re
import requests
import json


def get_one_page(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
    }
    res = requests.get(url, headers = headers)
    if res.status_code == 200:
        return res.text
    else:
        return None

def get_information(html):

    pattern = re.compile('<dd>.*?<i.*?board-index.*?>(.*?)</i>.*?<a.*?title="(.*?)".*?img\sdata-src="(.*?)".*?</a>.*?<p.*?star.*?>(.*?)</p>.*?<p.*?releasetime.*?>(.*?)</p>',re.S)
    datas = re.findall(pattern,html)
    for data in datas:
        yield {
            'index':data[0],
            'title':data[1],
            'imgSrc':data[2].strip(),
            'star':data[3].strip()[3:] if len(data[3].strip())>3 else '',
            'releaseTime':data[4].strip()[5:] if len(data[4].strip())>5 else''
        }

def write_to_json(content):
    with open('data.txt','a',encoding = 'utf-8') as f:
        f.write(json.dumps(content,ensure_ascii = False))


def main():
    for i in range(0,100,10):
        rawUrl = 'http://maoyan.com/board/4?offset='
        url = rawUrl+str(i)
        html = get_one_page(url)
        for item in get_information(html):
            write_to_json(item)


main()


### 抓取猫眼电影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、付费专栏及课程。

余额充值