Bootstrap

使用Python爬虫获取电影信息

此博客讲述了如何用python爬虫爬取电影信息。

首先要导入必要的数据库reques库和etree库。

import requests  # 网络请求模块
from lxml import etree  # 数据解析模块

请求头信息,把程序伪装成浏览器。

headers = {
    'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.467.400 QQBrowser/13.4.6232.400'
}

功能函数,出去第一个字符串

def get_first_text(list):
    try:
        return list[0].strip()  # 返回第一个字符串,除去两端的空格
    except:
        return ""  # 返回空字符串

爬取信息,这需要用到pandas库

df = pd.DataFrame(columns=["序号", "标题", "链接", "导演", "评分", "评价人数", "简介"])

# 使用列表生成式表示10个页面的地址
urls = ['https://movie.douban.com/top250?start={}&filter='.format(str(i * 25)) for i in range(10)]
count = 1  # 用来计数
for url in urls:
    res = requests.get(url=url, headers=headers)  # 发起请求
    html = etree.HTML(res.text)  # 将返回的文本加工为可以解析的html
    lis = html.xpath('//*[@id="content"]/div/div[1]/ol/li')  # 获取每个电影的li元素
    # 解析数据
    for li in lis:
        title = get_first_text(li.xpath('./div/div[2]/div[1]/a/span[1]/text()'))  # 电影标题
        src = get_first_text(li.xpath('./div/div[2]/div[1]/a/@href'))  # 电影链接
        dictor = get_first_text(li.xpath('./div/div[2]/div[2]/p[1]/text()'))  # 导演
        score = get_first_text(li.xpath('./div/div[2]/div[2]/div/span[2]/text()'))  # 评分
        comment = get_first_text(li.xpath('./div/div[2]/div[2]/div/span[4]/text()'))  # 评价人数
        summary = get_first_text(li.xpath('./div/div[2]/div[2]/p[2]/span/text()'))  # 电影简介
        print(count, title, src, dictor, score, comment, summary)  # 输出

        df.loc[len(df.index)] = [count, title, src, dictor, score, comment, summary]

        count += 1

通过以上代码可以爬取该网页的电影信息,

;