selenium实战脚本集(2)——简单的知乎爬虫

背景

很多同学在工作中是没有selenium的实战环境的,因此自学的同学会感到有力无处使,想学习但又不知道怎么练习。其实学习新东西的道理都是想通的,那就是反复练习。这里乙醇会给出一些有用的,也富有挑战的练习,帮助大家去快速掌握和使用selenium webdriver。多用才会有感触。

练习

到http://www.zhihu.com/explore这个页面,用selenium获取今日最热本月最热的文章标题和内容

用到的知识点

  • 爬虫知识。用webdriver去也页面上爬一些内容。用到的核心api是getAttribute;

  • 如何跳转到新页面

  • 观察能力,有些时候跳转tab是不需要点击的

参考代码

#ecoding: utf-8

"""
从zhihu.com获取每日最热和每月最热
"""

from selenium import webdriver
from datetime import date

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

class Zhihu:
	def __init__(self):
		self.daily_url = 'https://www.zhihu.com/explore#daily-hot'
		self.monthly_url = 'https://www.zhihu.com/explore#monthly-hot'

	def __enter__(self):
		self.dr = webdriver.Firefox()
		return self

	def __exit__(self, p1, p2, p3):
		self.dr.quit()

	def get_daily_hots(self):
		result = []
		hots_urls = self.get_daily_hots_urls()
		for url in hots_urls:
			result.append(self.get_answer(url))
		return result

	def get_answer(self, url):
		self.dr.get(url)
		# wrap_div = self.dr.find_element_by_css_selector('.zm-item-answer.zm-item-expanded')
		article = {}
		article['question'] = self.dr.find_element_by_css_selector('#zh-question-title').text
		article['author'] = self.dr.find_element_by_css_selector('.author-link').text
		article['answer'] = self.dr.find_element_by_css_selector('.zm-editable-content.clearfix').get_attribute('innerHTML')

		return article

	def get_monthly_hots(self):
		pass

	def get_daily_hots_urls(self):
		self.dr.get(self.daily_url)
		wrap_div = self.dr.find_element_by_class_name('tab-panel')
		title_url_elements = wrap_div.find_elements_by_class_name('question_link')
		assert len(title_url_elements) == 5
		urls = []
		for title in title_url_elements:
			urls.append(title.get_attribute('href'))
		return urls

if __name__ == '__main__':
	with Zhihu() as zhihu:
		articles = zhihu.get_daily_hots()

视频精讲

pass

常见错误

  • 这里有一个小技巧,就是获取回答的时候其实是不需要打开新窗口的,如参考代码所示
  • 每月的热点是不需要点击tab页的,直接通过url访问就好
  • 最好不要使用难以维护的xpath去定位,像/div[2]/span[1]/a[0]这种跟dom结构强相关的xpath就是难以维护的

挑战

试着自己补充完成get_monthly_hots()方法,注意代码的重用性

原文地址:https://www.cnblogs.com/nbkhic/p/4402118.html