【xpath】多个xpath Element对象,提取结果是一样的

every blog every motto: What doesn’t kill you makes you stronger.

0. 前言

用xpath提取,获取多个element对象,循环遍历提取其中内容结果是一样的,记录。

1. 正文

1.1 方法一:

comment_xpath = html.xpath('//div[@node-type="root_comment"]')
# 遍历每个评论块
for ele in comment_xpath:
    # t = etree.tostring(ele,encoding='utf-8')
    # print(t.decode('utf-8'))
    # print('----'*100)
    # 评论人昵称
    nick_name = ele.xpath('//div[@class="WB_text"]/a/text()')[0]
    print(nick_name)

在这里插入图片描述

1.2 方法二(加了一个.)

comment_xpath = html.xpath('//div[@node-type="root_comment"]')
# 遍历每个评论块
for ele in comment_xpath:
    # t = etree.tostring(ele,encoding='utf-8')
    # print(t.decode('utf-8'))
    # print('----'*100)
    # 评论人昵称
    nick_name = ele.xpath('.//div[@class="WB_text"]/a/text()')[0]
    print(nick_name)

在这里插入图片描述

1.3 分析(待解)

  1. 取消注释for循环中三条语句,将每个ele转成字符,可以发现结果都是不同的。不知道为什么不能正确提取其中的昵称(总是提取第一个)
  2. for循环内的xpath加“.”,表示“选取当前节点”,既然每个ele都不一样,为什么需要加"."呢?

1.4 原因

  1. // 默认从路径开始匹配,所以出现了上面的结果
  2. 如果想匹配当前路径ele下的东西,前面要"."

猜你喜欢

转载自blog.csdn.net/weixin_39190382/article/details/112634272