码迷,mamicode.com
首页 > 其他好文 > 详细

selenium:指挥浏览器工作

时间:2020-01-18 13:13:04      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:网页   opera   一个   tool   逻辑   fir   复杂   使用   rip   

selenium可以用几行代码,控制浏览器,做出自动打开、输入、点击等操作,就像是有一个真正的用户在操作一样。

在遇到页面交互复杂或是URL加密逻辑复杂的情况时,selenium就派上了用场,它可以真实地打开一个浏览器,等待所有数据都加载到Elements中之后,再把这个网页当做静态网页爬取就好了。

安装

pip install selenium

配置驱动

推荐的是Chrome浏览器,打开下面的链接,就可以下载Chrome的安装包了,Windows和Mac都有:

https://localprod.pandateacher.com/python-manuscript/crawler-html/chromedriver/ChromeDriver.html

 

其他浏览器驱动的下载地址:

Firefox浏览器驱动:geckodriver

IE浏览器驱动:IEDriverServer

Edge浏览器驱动:MicrosoftWebDriver

Opera浏览器驱动:operadriver

PhantomJS浏览器驱动:phantomjs

下载的驱动,要放在Python路径旁,即可正常使用驱动

简单案例

1.自动填充内容,并触发按钮的点击:

技术图片

from selenium import webdriver
import time

# 设置浏览器引擎
driver = webdriver.Chrome()

# 请求网页
url = https://localprod.pandateacher.com/python-manuscript/hello-spiderman/
driver.get(url)
time.sleep(2)

# 获取输入框,并填充内容
teacher = driver.find_element_by_id(teacher)
# 输入文字
teacher.send_keys(酱酱)

# 获取输入框,并填充内容
assistant = driver.find_element_by_name(assistant)
# 输入文字
assistant.send_keys(都喜欢)

time.sleep(2)

# 清除元素内容
teacher.clear()
time.sleep(2)
teacher.send_keys(蜘蛛侠)

# 获取按钮,并触发点击事件
sub = driver.find_element_by_class_name(sub)
# 点击按钮
sub.click()

time.sleep(2)

# 关闭浏览器
driver.close()

 

2.爬取QQ音乐精彩评论:

使用的是静默模式(浏览器默默运行,并不会弹出)

技术图片

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

# 设置静默模式
chrome_options = Options()
chrome_options.add_argument(--headless)

# driver = webdriver.Chrome()
driver = webdriver.Chrome(options=chrome_options) # 浏览器在后台默默运行
print(正请求网页内容...)
driver.get(https://y.qq.com/n/yqq/song/000xdZuV2LcQ19.html)
time.sleep(2)

print(加载更多...)
# 点击加载更多
more_hot_btn = driver.find_element_by_class_name(js_get_more_hot)
more_hot_btn.click()

time.sleep(1)

print(获取评论...)
# 获取评论
comments = driver.find_element_by_class_name(js_hot_list).find_elements_by_class_name(js_cmt_li)
for comment in comments:
    print(comment.find_element_by_class_name(js_hot_text).text)
    print("")

driver.close()

 

其他资料:

1.selenium官方文档:https://selenium.dev/selenium/docs/api/py/api.html

2.selenium中文翻译文档:https://selenium-python-zh.readthedocs.io/en/latest/

3.设置浏览器驱动:https://www.cnblogs.com/muxs/p/11346740.html

4.基础入门:https://www.jianshu.com/p/1531e12f8852

 

selenium:指挥浏览器工作

标签:网页   opera   一个   tool   逻辑   fir   复杂   使用   rip   

原文地址:https://www.cnblogs.com/KeenLeung/p/12208487.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!