爬虫之requests+xpath的简单使用---提取html中的数据

本文通过Python和lxml库解析豆瓣电影榜单页面,提取电影名称、URL、图片URL、评论数及评分等信息,展示了如何使用XPath定位和抓取网页数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里获取电影名称的时候有点复杂了,使用正则的话可能会相对简单一些

import requests
from lxml import etree

url = "https://movie.douban.com/chart"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36"
}

response = requests.get(url, headers=headers)
html_str = response.text
# print(html_str)

# 拿到html_str后就可以使用etree.HTML()方法获取html对象,之后就可以使用xpath方法了
html = etree.HTML(html_str)  # <Element html at 0x7ff3fe0d6108>

# ①获取所有电影的url地址 (直接定位到标签)
url_list = html.xpath("//div[@class='pl2']/a/@href")

# ②获取所有电影图片的地址 (直接定位到标签)
image_list = html.xpath("//a[@class='nbg']/img/@src")

# ③获取每部电影的名称,电影url,图片url,评论数,评分等 
    # 思路:经过分析html发现,其实每一部电影都是存在于一个table标签中的,那么可以先按照table分组,然后从每个table分组中提取想要的数据
# 1-- 以每个电影分组
table_obj = html.xpath("//div[@class='indent']/div/table")
# 2-- 从html内容知道,电影名称分为两部分,先构造电影名字
name1_list = []
name2_list = []
for table in table_obj:
    for name1 in table.xpath(".//div[@class='pl2']/a/text()"):
        if "/" in name1:
            name1_list.append(name1.replace("/", "").strip())
    for name2 in table.xpath(".//div[@class='pl2']/a/span/text()"):
        name2_list.append(name2)
name_list = []
for index in range(len(name1_list)):
    name_list.append(name1_list[index]+"/"+name2_list[index])

# 构造电影字典
movie_dict = {}
index = 0
for table in table_obj:
    # 由于取到的结果是列表,可以取第0个元素,你可以把这一步去掉,那么对应的结果则是列表格式
    movie_dict["href_url"] = table.xpath(".//div[@class='pl2']/a/@href")[0] if len(table.xpath(".//div[@class='pl2']/a/@href")) != 0 else None
    movie_dict["img_url"] = table.xpath(".//a[@class='nbg']/img/@src")[0] if len(table.xpath(".//a[@class='nbg']/img/@src")) != 0 else None
    movie_dict["comment"] = table.xpath(".//span[@class='pl']/text()")[0] if len(table.xpath(".//span[@class='pl']/text()")) != 0 else None
    movie_dict["rating"] = table.xpath(".//span[@class='rating_nums']/text()")[0] if len(table.xpath(".//span[@class='rating_nums']/text()")) != 0 else None
    movie_dict["movie_name"] = name_list[index]
    index += 1
    print(movie_dict)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值