selenium与xpath之获取指定位置的元素的实现

作者:封妖师的徒弟 时间:2022-01-14 12:02:35 

今天有点新的与大家分享,关于selenium与xpath之间爬数据获取指定位置的时候,方式不一样哦。

详情可以看我的代码,以b站来看好吧:

selenium与xpath之获取指定位置的元素的实现

查看这href元素,如果是xpath,肯定这么写是没有问题的:


i.find_element_by_xpath('./a/@href')

但你再selenium里面这样写会报错,所以要改成这样


i.find_element_by_xpath('./a').get_attribute('href')

这样方可正确

这是一个小案例,关于爬取b站音乐视频,但我的技术水平有限,无法下载,找不到那个东东

大家如果知道如何下载可以在评论区留言,嘿嘿


import requests
from selenium.webdriver import Chrome,ChromeOptions
#后面越来越多喜欢用函数来实现了
def get_webhot():  #热搜函数
 headers = {
   'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'
 }
 url ="https://www.bilibili.com/" # 微博的地址

res = requests.get(url)
 #这个就是再后台上面运行那个浏览器,不在表面上占用你的
 option = ChromeOptions()
 option.add_argument('--headless')
 option.add_argument("--no-sandbox")
 #这里也要输入
 browser = Chrome(options=option)
 browser.get(url)
 #解析那个web热搜前,按住ctrl+f会在下面出现一个框框,然后改就完事
 browser.find_element_by_xpath('//*[@id="primaryChannelMenu"]/span[3]/div/a/span').click()
 c = browser.find_elements_by_xpath('//*[@id="high_energy"]/div[1]/div[2]/div')
 for i in c:
   #这里一定要注意,在selenium中不能像xpath那样写('./a/@href')来获取指定的位置,要报错,只能这么获取,查了很久
   detail_url = i.find_element_by_xpath('./a').get_attribute('href')
   name = i.find_element_by_xpath('./a/p').get_attribute('title')
   detail_page_text = requests.get(url=detail_url,headers = headers).text
   print(detail_url,name)
#运行完事
get_webhot()

这是这个结果

selenium与xpath之获取指定位置的元素的实现

来源:https://blog.csdn.net/XY52wiue/article/details/113007578

标签:selenium,xpath,元素
0
投稿

猜你喜欢

  • 解决Python 使用h5py加载文件,看不到keys()的问题

    2021-10-04 06:19:15
  • pandas中read_csv、rolling、expanding用法详解

    2022-03-01 06:09:30
  • Python基础入门之seed()方法的使用

    2021-11-17 04:10:19
  • python编程的核心知识点总结

    2023-09-26 21:24:24
  • python实现复制整个目录的方法

    2023-04-08 18:14:47
  • 利用Python 实现图片转字符画

    2022-05-06 11:31:01
  • python中input()与raw_input()的区别分析

    2023-02-12 14:08:36
  • PHP date函数参数详解

    2023-11-23 06:41:40
  • 深入了解Hybrid App技术的相关知识

    2023-08-10 09:36:02
  • Python中函数及默认参数的定义与调用操作实例分析

    2022-01-15 05:16:31
  • show一下刚做的系统登录界面

    2008-09-13 19:13:00
  • MySQL复制的概述、安装、故障、技巧、工具

    2011-04-11 08:36:00
  • FFrpc python客户端lib使用解析

    2023-09-06 00:12:20
  • Python 异步之生成器示例详解

    2023-01-12 04:34:26
  • Python import自定义模块方法

    2022-08-23 06:57:27
  • python+splinter自动刷新抢票功能

    2023-07-08 11:33:42
  • 一篇文章带你入门python之推导式

    2022-02-05 08:29:35
  • Python FTP操作类代码分享

    2022-09-07 17:59:23
  • js对象基础实例分析

    2023-09-03 12:07:56
  • 《色彩解答》系列之二 色彩比例

    2008-02-17 14:38:00
  • asp之家 网络编程 m.aspxhome.com