selumium 中 xpath获取文本、属性正确写法
报错“The result of the xpath expression is: [object Attr]. It should be an element”
yutube爬虫动态加载,需要用到selenium-webdriver,使用过程中,首先使用
find_elements_by_xpath进行批量标签的定位选取,之后
使用find_element_by_xpath精细筛选选标签的时候出现上面错误提示,
原因是这个webdriver的定位方法和浏览器xpath不一样,不能直接定位到标签的属性
需要首先定位到webelement,之后get到属性
正确
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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现