selumium中xpath获取文本、属性正确写法

xpath不同库的用法不一样,学习一门编程语言真的太难了,看完基本语法,会做题了,你以为会了,结果实战起来各种问题都来了。xpath不同库的方法不一样的。selumium中如何获取属性和文本呢。我用text获取属性,各种报错。

selenium不支持xpath中直接获取text,报错:selenium Message: invalid selector: The result of the xpath 

selenium中text直接获取xpath属性会报错:The result of the xpath expression is: [object Attr]. It should be an element错误

应该使用get_attribute来获取属性值:

正确写法:

try:
                temp['host_url'] = node.find_element_by_xpath('./div/div/div/ytd-video-meta-block/div/div/div/yt-formatted-string/a').get_attribute('href')
            except Exception as e:
                print(e)
            try:
                temp['show_url'] = node.find_element_by_xpath('./div/ytd-thumbnail/a').get_attribute('href')
            except Exception as e:
                print(e)
            try:
                temp['title'] = node.find_element_by_xpath('./div/div/div[1]/div/h3/a').get_attribute('title')
            except Exception as e:
                print(e)
            try:
                temp['user'] = node.find_element_by_xpath('./div/div/div/ytd-video-meta-block/div/div/div/yt-formatted-string/a').text
            except Exception as e:

 

错误写法:

try:
                temp['host_url'] = node.find_element_by_xpath('./div/div/div/ytd-video-meta-block/div/div/div/yt-formatted-string/a/@href')
            except Exception as e:
                print(e)
            try:
                temp['show_url'] = node.find_element_by_xpath('./div/ytd-thumbnail/a/@href')
            except Exception as e:
                print(e)
            try:
                temp['title'] = node.find_element_by_xpath('./div/div/div[1]/div/h3/a/@title')
            except Exception as e:
                print(e)
            try:
                temp['user'] = node.find_element_by_xpath('./div/div/div/ytd-video-meta-block/div/div/div/yt-formatted-string/a/text()')
            except Exception as e:
                print(e)