目标网站
这是评论页
思路是先获取这一页全部歌曲的url,然后再逐个访问url获取评论
这里主要还是切换iframe的问题
打开歌曲的评论页后由于刷新了页面,要再切进iframe
结果:
完整代码:
import time
from selenium import webdriver
class Song_Spider():
def __init__(self):
self.url = 'https://music.163.com/#/playlist?id=2698698442'
# 创建浏览器 对象
self.window = webdriver.Chrome('./chromedriver')
self.song_url_list = []
def get_first_page(self):
self.window.get(self.url) # 在当前窗口中访问网址
frame = self.window.find_element_by_id('g_iframe')
self.window.switch_to.frame(frame)
def get_song_url_list(self):
song_element_list = self.window.find_elements_by_xpath('//table[@class="m-table "]/tbody/tr/td[2]/div/div/div/span/a')
for element in song_element_list:
self.song_url_list.append(element.get_attribute('href'))
print(self.song_url_list)
def get_song_comment(self):
for song_url in self.song_url_list:
self.window.get(song_url)
frame = self.window.find_element_by_id('g_iframe')
self.window.switch_to.frame(frame)
time.sleep(2)
comments = self.window.find_elements_by_xpath('//div[@class="itm"]/div[2]/div/div')
for comment in comments: # 只爬了一页的评论,没有做翻页
print(comment.text)
print('*'*50)
if __name__ == '__main__':
spider = Song_Spider()
spider.get_first_page()
time.sleep(2)
spider.get_song_url_list()
spider.get_song_comment()
spider.window.quit()