爬取流程
- 导入selenium模块中的webdriver包
- 实例化webdriver
- 准备url
- 打开网页
- 定位标签元素
- 执行动作
- 获取需要的信息
- 关闭浏览器
新实例
# 新版本
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
import time
# 创建一个对象
web = Chrome()
# 打开浏览器
web.get("https://www.baidu.com")
# 获取元素
el = web.find_element(By.CSS_SELECTOR,'#s-top-left>a') # css选择器定位
print(el)
time.sleep(1) # 延时一秒钟
web.quit() # 关闭浏览器
旧实例
# 旧版本
from selenium import webdriver
import time
# 实例化驱动
web = webdriver.Chrome()
# 打开百度
web.get('https://www.baidu.com/')
title = web.find_element_by_xpath('//*[@id="s-top-left"]/a[1]')
print(title.text) # 输出
time.sleep(1) # 延时一秒
web.close() # 关闭浏览器
常用的元素定位方法
新方法
web.find_element(By.ID, 's-top-left') # 元素id定位
web.find_element(By.CLASS_NAME,'mnav') # 类选择器定位
web.find_element(By.TAG_NAME, 'a') # 元素标签定位
web.find_element(By.NAME,'description') # name属性选择器
web.find_element(By.LINK_TEXT,'新闻') # 通过文字连接选择
web.find_element(By.PARTIAL_LINK_TEXT, '新') # 通过部分文字连接选择
web.find_elements(By.XPATH, '//*[@id="s-top-left"]/a') # xpath选择器
web.find_element(By.CSS_SELECTOR,'#s-top-left>a') # css选择器定位
旧方法
find_element_by_id(id的值) # 通过元素的id来定位
find_element_class_name(class的值) # 通过class属性来定位元素
find_element_by_tag_name(标签的名字) # 通过标签的名字来定位
find_element_by_css_selector(css选择器) # 通过css样式定位元素
find_element_by_name(节点中的name的值) # 通过标签的name来定位
find_element_by_link_text(文字链接) # 通过文字链接来定位元素
find_element_by_partial_link_text() # 通过部分文字链接来定位素
driver.find_element_by_xpath(x_path) # 通过xpth()来定位
执行动作
# 定位元素
input = el = web.find_elements(By.CSS_SELECTOR, '#s-top-left>input')[0]
# 给元素发送消息
input.send_keys('Python')
# 回车操作
input.send_keys(Keys.ENTER)
# 点击事件
input.click()
# 清除消息
input.clear()
执行JavaScript代码
# 可以直接执行js代码
driver.execute_script('alert("直接执行js")')
获取元素文本值和属性
# 获取元素
name = browser.find_element_by_id('s')
# 获取元素的文本值
print(name.text)
# 获取元素的属性
print(name.get_attribute('href'))
打卡第64天,对python大数据感兴趣的朋友欢迎一起讨论、交流,请多指教!
本文介绍了Python爬虫中selenium模块的使用,包括爬取流程、元素定位方法、执行动作、JavaScript代码操作及获取元素信息。通过实例讲解了如何打开网页、定位元素、执行交互操作,最后分享了获取元素文本和属性的方法。
3万+

被折叠的 条评论
为什么被折叠?



