0


【爬虫】selenium实战--爬取知乎评论

🍬 博主介绍


  • 👨‍🎓 博主介绍:大家好,我是可可卷,很高兴和大家见面~
  • ✨主攻领域:【数据分析】【机器学习】 【深度学习】 【数据可视化】
  • 🎉欢迎关注💗点赞👍收藏⭐️评论📝
  • 🙏作者水平很有限,欢迎各位大佬指点,一起学习进步!

🍭0 教程说明


使用selenium可以直接获得加载后的网页信息而无需考虑请求信息,Ajax,js解密等等,可谓偷懒神器,下面以 你读懂带土了吗? - 知乎https://www.zhihu.com/question/375762710 为例,进行实战讲解


特殊声明:本教程仅供学习,若被他人用于其他用途,与本人无关

🥚🥚🥚我是分割线🥚🥚🥚

🍭1 分析url


分析网址,可以发现网址是https://www.zhihu.com/question/ + question_id,因此可以通过下述代码构建url:

  1. try:
  2. option = webdriver.ChromeOptions()
  3. option.add_argument("headless")
  4. option.add_experimental_option("detach", True)
  5. driver = webdriver.Chrome(chrome_options=option)
  6. driver.get('https://www.zhihu.com/question/'+question_id)
  7. except Exception as e:
  8. print(e)
  9. finally:
  10. driver.close()

🥚🥚🥚我是分割线🥚🥚🥚

🍭2 关闭登录弹窗


进入网页,由于未登录,因此会出现登录弹窗,我们可以通过Xpath和CSS选择器的方式获取关闭按钮,模拟点击操作

  1. # 先触发登陆弹窗。
  2. WebDriverWait(driver, 40, 1).until(EC.presence_of_all_elements_located(
  3. (By.CLASS_NAME, 'Modal-backdrop')), waitFun())
  4. # 关闭登陆窗口
  5. driver.find_element_by_xpath('//button[@class="Button Modal-closeButton Button--plain"]').click()

🥚🥚🥚我是分割线🥚🥚🥚

🍭3 获取所有答案


由于知乎是动态加载,需要将滚轮滑动到底部才能获得全部答案,因此需要运行js获得页面高度,并模拟滚轮下滑

  1. def waitFun():
  2. js = """
  3. let equalNum = 0;
  4. window.checkBottom = false;
  5. window.height = 0;
  6. window.intervalId = setInterval(()=>{
  7. let currentHeight = document.body.scrollHeight;
  8. if(currentHeight === window.height){
  9. equalNum++;
  10. if(equalNum === 2){
  11. clearInterval(window.intervalId);
  12. window.checkBottom = true;
  13. }
  14. }else{
  15. window.height = currentHeight;
  16. window.scrollTo(0,window.height);
  17. window.scrollTo(0,window.height-1000);
  18. }
  19. },1500)"""
  20. driver.execute_script(js)
  21. def getHeight(nice):
  22. js = """
  23. return window.checkBottom;
  24. """
  25. return driver.execute_script(js)
  26. # 当滚动到底部时
  27. WebDriverWait(driver, 40, 3).until(getHeight, waitFun())
  28. # 等待加载
  29. sleep(1)

🥚🥚🥚我是分割线🥚🥚🥚

🍭4 获取标题和副标题


需要注意,有些问题是没有副标题的,因此也不存在副标题的element

  1. title=driver.find_element_by_xpath('//h1[@class="QuestionHeader-title"]').text
  2. subtitle = driver.find_element_by_xpath('//span[@class="RichText ztext css-hnrfcf"]').text

🥚🥚🥚我是分割线🥚🥚🥚

🍭5 展开评论


由于评论的数据并不包含在页面中,而需要点击 “XX条评论” 按钮后才进行动态加载,因此需要模拟点击这些按钮

  1. wait=WebDriverWait(driver,30) #显式等待
  2. path=(By.XPATH,'//button[@class="Button ContentItem-action Button--plain Button--withIcon Button--withLabel"]')
  3. clicks=wait.until(EC.presence_of_all_elements_located(path))
  4. for c in clicks:
  5. if '条' in c.text:
  6. driver.execute_script("arguments[0].click();", c)
  7. sleep(0.1)

🥚🥚🥚我是分割线🥚🥚🥚

🍭6 按块获取答案


先分析得到每一个问题的答主信息、回答内容、评论都在 “List-item”下


然后在每一块元素的基础上,在进行答主信息、回答内容、评论的查找

  1. # get blocks
  2. blocks=driver.find_elements_by_xpath('//div[@class="List-item"]')
  3. res=[]
  4. for b in blocks:
  5. author = b.find_element_by_xpath('.//div[@class="ContentItem-meta"]//meta[@itemprop="name"]').get_attribute('content')
  6. content = b.find_element_by_xpath('.//div[@class="RichContent-inner"]').text
  7. # button=b.find_element_by_xpath('.//div[@class="ContentItem-actions"]//button[contains(text(),"评论")]')
  8. button=b.find_element_by_xpath('.//button[@class="Button ContentItem-action Button--plain Button--withIcon Button--withLabel"]')
  9. if '收起' in button.text:
  10. comment = b.find_elements_by_xpath('.//ul[@class="NestComment"]')
  11. comments=''
  12. for c in comment:
  13. comments+=c.text
  14. print(comments)
  15. sleep(0.2)
  16. else:
  17. comments = '无评论'
  18. tmp={'author':author,'content':content,'comments':comments}
  19. res.append(tmp)

🥚🥚🥚我是分割线🥚🥚🥚

🍭7 保存信息



🍥7.1 json

  1. json_str = json.dumps(res)
  2. with open(filename+'.json', 'w',encoding='utf-8') as json_file:
  3. json_file.write(json_str)

🍥7.2 csv

  1. df = pd.DataFrame(res)
  2. df.to_csv(filename+'.csv')

🍥7.3 txt

  1. cwd=os.getcwd()
  2. with open(cwd++filename+'.txt','a',encoding='utf-8')as f:
  3. for i,r in enumerate(res):
  4. f.write(f'第{i+1}个回答'.center(30,'='))
  5. f.write('\n')
  6. f.write(f'author:{r["author"]}\n')
  7. f.write(f'content:{r["content"]}\n')
  8. f.write(f'comments:\n{r["comments"]}\n')

🍥7.4 数据库

通过pymysql或pymongo保存到数据库中,有兴趣的可以再去了解

🥚🥚🥚我是分割线🥚🥚🥚

🍭8 结语


不知道大家在爬取之前,是否注意到知乎遵循了robots协议(没有关注过的可以点击这个网址:https://www.zhihu.com/robots.txt)

为了不给网站的管理员带来麻烦,希望大家在爬取的时候能尽量遵循robots协议;若在学习过程中在不可避免地无法遵循robots协议,也尽量维持爬虫爬取频率与人类正常访问频率相当,不过多占用服务器资源。

标签: 爬虫 selenium python

本文转载自: https://blog.csdn.net/weixin_45825073/article/details/122094486
版权归原作者 可可卷 所有, 如有侵权,请联系我们删除。

“【爬虫】selenium实战--爬取知乎评论”的评论:

还没有评论