环境配置:Google Chrome + chromedriver(版本要与Chrome相同,chromedriver.exe放到python.exe所在的文件目录下)+ selenium 3.141.0
# # 本地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,在后台默默运行
from selenium import webdriver
import time
# from bs4 import BeautifulSoup
# 设置引擎为Chrome,真实地打开一个Chrome浏览器
driver = webdriver.Chrome()
# 打开网页
driver.get('https://y.qq.com/n/yqq/song/000xdZuV2LcQ19.html')
time.sleep(2)
# 获取并点击”加载更多“按钮
button = driver.find_element_by_class_name('js_get_more_hot')
# 更多方法--作用
# find_element(s)_by_tag_name 通过元素的标签名称选择
# find_element(s)_by_class_name 通过元素的class属性选择
# find_element(s)_by_id 通过元素的id选择
# find_element(s)_by_name 通过元素的name属性选择
# find_element(s)_by_link_text 通过链接文本获取超链接
# find_element(s)_by_partial_link_text 通过链接的部分文本获取超链接
button.click()
# 更多操作方法--作用
# .clear() 清楚元素的内容
# .send_keys() 模拟按键输入,自动填写表单
time.sleep(2)
# 第一种解析方法:单单使用selenium
comments = driver.find_element_by_class_name('js_hot_list').find_elements_by_class_name('js_cmt_li')
# 第二种解析方法:使用selenium和BeautifulSoup结合
# pageSource = driver.page_source
# soup = BeautifulSoup(pageSource, 'html.parser')
# comments = soup.find('ul', class_='js_hot_list').find_all('li', class_='js_cmt_li')
print(len(comments))
for comment in comments:
sweet = comment.find_element_by_tag_name('p')
# sweet = comment.find('p')
print('评论:%s\n ---\n' % sweet.text)
# 关闭网页
driver.close()