Python爬虫学习之selenium库

目录

一、selenium库的基本使用

二、selenium元素定位

三、selenium元素信息

四、selenium交互


一、selenium库的基本使用

复制代码
#(1)导入selenium
from selenium import webdriver

#(2)创建浏览器操作对象
path = 'chromedriver.exe'

browser = webdriver.Chrome(path)

#(3)访问网站
url = 'https://www.jd.com'

browser.get(url)

#page_source获取网页源码
content = browser.page_source
print(content)

二、selenium元素定位

复制代码
from selenium import webdriver

path = 'chromedriver.exe'

browser = webdriver.Chrome(path)

url = 'http://wwww.baidu.com'

browser.get(url)

#元素定位

#根据id来找到对象(常用)
button = browser.find_element_by_id('su')
print(button)

#根据标签属性的属性值来获取对象
button = browser.find_element_by_name('wd')
print(button)

#根据xpath语句来获取对象(常用)
button = browser.find_element_by_xpath('//input[@id="su"]')
print(button)

#根据标签的名字来获取对象
button = browser.find_elements_by_tag_name('input')
print(button)

#使用的bs4的语法来获取对象(常用)
button = browser.find_elements_by_css_selector('#su')
print(button)

button = browser.find_element_by_link_text('地图')
print(button)

三、selenium元素信息

复制代码
from selenium import webdriver

#访问元素信息
#(1)获取元素属性
#(2)获取元素文本
#(3)获取标签名

path = 'chromedriver.exe'
browser = webdriver.Chrome(path)

url = 'http://www.baidu.com'

browser.get(url)

#(1)获取元素属性
input = browser.find_element_by_id('su')

print(input.get_attribute('class'))   #里面放属性名字

#(2)获取元素文本
A = browser.find_element_by_link_text('新闻')
print(A.text)

#(3)获取标签名
print(input.tag_name)

四、selenium交互

e.g.

复制代码
from selenium import webdriver

#创建浏览器对象
path = 'chromedriver.exe'

browser = webdriver.Chrome(path)

#定义url
url = 'http://wwww.baidu.com'

browser.get(url)

import time
time.sleep(3)

#获取文本框的对象
input = browser.find_element_by_id('kw')

#在文本框中输入Python
input.send_keys('Python')

time.sleep(2)

#获取百度一下的按钮
button = browser.find_element_by_id('su')

#点击百度一下按钮
button.click()

time.sleep(2)

#模拟js滑动  滑动到底部
db_button = 'document.documentElement.scrollTop=100000'
browser.execute_script(db_button)

time.sleep(2)

#获取下一页的按钮的两种方法
#next = browser.find_element_by_css_selector('.n')

next = browser.find_element_by_xpath('//a[@class="n"]')

#点击下一页按钮
next.click()

time.sleep(2)

#回到上一页
browser.back()

time.sleep(2)

#回去
browser.forward()

time.sleep(3)

#退出
browser.quit()
相关推荐
A7bert77710 分钟前
【YOLOv8-obb部署至RK3588】模型训练→转换RKNN→开发板部署
linux·c++·人工智能·python·yolo
cdg==吃蛋糕32 分钟前
selenium 使用方法
开发语言·python
Y1nhl1 小时前
力扣_二叉树的BFS_python版本
python·算法·leetcode·职场和发展·宽度优先
Q_Q5110082852 小时前
python的婚纱影楼管理系统
开发语言·spring boot·python·django·flask·node.js·php
若兰幽竹2 小时前
【从零开始编写数据库:基于Python语言实现数据库ToyDB的ACID特性】
数据库·python
xiaocainiao8812 小时前
Python 实战:构建 Git 自动化助手
git·python·自动化
nightunderblackcat3 小时前
新手向:使用Python将多种图像格式统一转换为JPG
开发语言·python
engchina3 小时前
Python PDF处理库深度对比:PyMuPDF、pypdfium2、pdfplumber、pdfminer的关系与区别
开发语言·python·pdf
Lo-Y-eH3 小时前
Openpyxl:Python操作Excel的利器
python·excel
DAWN_T173 小时前
Transforms
pytorch·python·机器学习·jupyter·pycharm