美文网首页
python爬虫9:selenium

python爬虫9:selenium

作者: Iphone60Plus | 来源:发表于2020-06-02 10:38 被阅读0次

selenium是什么?
可以模拟实例化浏览器来完成数据提取

# 本地Chrome浏览器的可视模式设置:
from selenium import webdriver #从selenium库中调用webdriver模块
driver = webdriver.Chrome() # 设置引擎为Chrome,真实地打开一个Chrome浏览器

通常在本地环境中,将浏览器设置为静默模式

# 本地Chrome浏览器的静默默模式设置:
from selenium import  webdriver #从selenium库中调用webdriver模块
from selenium.webdriver.chrome.options import Options # 从options模块中调用Options类

chrome_options = Options() # 实例化Option对象
chrome_options.add_argument('--headless') # 把Chrome浏览器设置为静默模式
driver = webdriver.Chrome(options = chrome_options) # 设置引擎为Chrome,在后台默默运行

解析和提取方法


image.png
image.png

selenium还可以搭配BeautifulSoup解析提取数据,前提是先获取字符串格式的网页源代码。

HTML源代码字符串 = driver.page_source
image.png

selenium优缺点
优:简单直观
缺:真实模拟,网页缓冲,速度较慢

#本地浏览器设置方法
from selenium import webdriver #从selenium库调用webdriver方法
import time #调用time模块
driver = webdriver.Chrome() #设置引擎为CHROME,真实打开一个浏览器

driver.get('https://localprod.pandateacher.com/python-manuscript/hello-spiderman/')
# 访问网页
time.sleep(2)

teacher = driver.find_element_by_id('teacher')
# 找到【请输入你喜欢的老师】下面的输入框位置
teacher.send_keys('吴枫')
# 输入文字
teacher.clear()
# 清除文字
teacher.send_keys('蜘蛛侠')
assistant = driver.find_element_by_name('assistant')
# 找到【请输入你喜欢的助教】下面的输入框位置
assistant.send_keys('都喜欢')
# 输入文字
button = driver.find_element_by_class_name('sub')
# 找到【提交】按钮
button.click()
# 点击提交
time.sleep(1)

driver.close()

相关文章

网友评论

      本文标题:python爬虫9:selenium

      本文链接:https://www.haomeiwen.com/subject/lagyzhtx.html