selenium库的使用
偶得一不错的爬虫教程,现博客分享,想要获取完整教程,加V:ff17328081445。文章为系列文章,持续更新,欢迎关注。
#实例爬取周杰伦歌曲评论
#!/usr/bin/python3
# 本地Chrome浏览器的静默默模式设置:
from selenium import webdriver #从selenium库中调用webdriver模块
from selenium.webdriver.chrome.options import Options # 从options模块中调用Options类
import time
chrome_options = Options() # 实例化Option对象
chrome_options.add_argument('--headless') # 把Chrome浏览器设置为静默模式
driver = webdriver.Chrome(options = chrome_options) # 设置引擎为Chrome,在后台默默运行
driver.get('https://y.qq.com/n/yqq/song/000xdZuV2LcQ19.html') # 访问页面
time.sleep(2)
comments = driver.find_element_by_class_name('js_hot_list').find_elements_by_class_name('js_cmt_li') # 使用class_name找到评论
print(len(comments)) # 打印获取到的评论个数
for comment in comments: # 循环
sweet = comment.find_element_by_tag_name('p') # 找到评论
print ('评论:%s\n ---\n'%sweet.text) # 打印评论
driver.close() # 关闭浏览器
>>>>>>>>>>>>>>>>>>>>>>>>
评论:我以前不喜欢周杰伦,也不喜欢他唱的所有歌,后来我朋友向我推荐这首歌,我听了之后才知道有多么好听。
---
评论:这首歌让我想起了他,因为他也给我唱过。可惜当年没能好好珍惜,如今却是后悔了!不过今后如何,我都祝福你!
---
PS:#selenium库具备解析数据、提取数据的能力。它和BeautifulSoup的底层原理一致,但在一些细节和语法上有所出入。
#首先明显的一个不同即是:selenium所解析提取的,是Elements中的所有数据,而BeautifulSoup所解析的则只是Network中第0个请求的响应。
自动操作浏览器
#!/usr/bin/python3
# 本地Chrome浏览器设置方法
from selenium import webdriver # 从selenium库中调用webdriver模块
import time # 调用time模块
driver = webdriver.Chrome() # 设置引擎为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('必须是发发') # 输入文字
time.sleep(2) # 暂停两秒,等待浏览器缓冲
assistant = driver.find_element_by_name('assistant') # 找到【请输入你喜欢的助教】下面的输入框位置
assistant.send_keys('都喜欢') # 输入文字
time.sleep(2) # 暂停两秒,等待浏览器缓冲
button = driver.find_element_by_class_name('sub') # 找到【提交】按钮
button.click() # 点击【提交】按钮
driver.close() # 关闭浏览器