python+seleniumで今日最も暑いことと今月最も暑いことを知っている最初の3つの質問と各質問の最初の答えを捕まえてhtmlファイルに保存します

3354 ワード

今日最も暑いことと今月最も暑いことを知っている最初の3つの質問と各質問の最初の答えをつかんで、htmlファイルに保存して、このhtmlファイルのファイル名は20160228_であるべきですzhihu_today_hot.html、つまり日付+zhihu_today_hot.html
コードは次のとおりです.
from selenium import webdriver
from time import sleep
import time

class ZhiHu():

   def __init__(self):
      self.dr = webdriver.Chrome()
      self.dr.maximize_window()
      self.today_hot_list = self.get_today_hot()
      self.month_hot_list = self.get_month_hot()

   def get_today_hot(self):
      '''         3 '''
      today_hot = []
      i = 0
      while i h2>a.question_link')[i].text #    
         question_answer_url = self.dr.find_elements_by_css_selector('div.explore-feed.feed-item>h2>a.question_link')[i].get_attribute('href') #       url
         self.dr.get(question_answer_url) #    url
         sleep(10)
         question_answer_innerhtml = self.dr.find_element_by_css_selector('.zm-editable-content.clearfix').get_attribute('innerHTML') #       innerHTML
         today_hot.append((question_title, question_answer_innerhtml))
         i += 1
      return today_hot

   def write_today_data(self):
      file_date = time.strftime('%Y-%m-%d',time.localtime(time.time()))
      self.file = open(file_date+'_zhihu_today_hot'+'.html','wb')
      file_line = '**********************************************
' #
      for item in self.today_hot_list:          self.file.write(file_line.encode('gbk'))          self.file.write((' :'+item[0]+'
').encode('gbk'))          self.file.write((' :'+item[1]+'
').encode('gbk'))       self.file.close()    def get_month_hot(self):       ''' 3 '''       month_hot = []       i = 5  #  5 explore-feed feed-item div , explore-feed.feed-item div i 5       while i h2>a.question_link')[i].text  #           question_answer_url = self.dr.find_elements_by_css_selector('div.explore-feed.feed-item>h2>a.question_link')[i].get_attribute('href')  #  url          self.dr.get(question_answer_url)  #  url          sleep(5)          question_answer_innerhtml = self.dr.find_element_by_css_selector('.zm-editable-content.clearfix').get_attribute('innerHTML')  #  innerHTML          month_hot.append((question_title, question_answer_innerhtml))          i += 1       return month_hot    def write_month_data(self):       file_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))       self.file = open(file_date + '_zhihu_mouth_hot' + '.html', 'wb')       file_line = '--------------------------------------
'       for item in self.month_hot_list:          self.file.write(file_line.encode('gbk'))          self.file.write((' :' + item[0] + '
').encode('gbk'))          self.file.write((' :' + item[1] + '
').encode('gbk'))       self.file.close()    def quit(self):       self.dr.quit() if __name__ == '__main__':    zhihu = ZhiHu()    zhihu.write_today_data()    zhihu.write_month_data()    zhihu.quit()

Webページは次のとおりです.
htmlを生成するには、次のようにします.
ほほほ、htmlのレイアウトはあまりよくありません~