爬什么 把斗鱼直播的所有房间信息爬取到本地并保存。
  
怎么做 为了练习selenium模块驱动无头浏览器进行爬虫,导入selenium的webdriver模块进行爬虫。
找到目标数据的请求url 
提取数据 
保存数据 
 
本来是要练习发送翻页请求,但是现在斗鱼网站的翻页按钮不在html响应体中,可能是由js生成,目前的知识水平还无法完成翻页。所以,就只是抓取了第一页的数据。find_element_by_xpath,但是我实验了多次,这个定位方式有问题。于是换了以前学过的方式,用lxml的etree模块将html响应转换为html对象,再对这个html对象做xpath。driver.page_source。
代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 from  selenium import  webdriverfrom  lxml import  etreeimport  jsonclass  DouyuSpider :    def  __init__ (self ):         self.strat_url = "https://www.douyu.com/directory/all"          self.driver = webdriver.Chrome(r"E:\chromedriver_win32\chromedriver.exe" )     def  get_content_list (self ):         page_source = self.driver.page_source                   html = etree.HTML(page_source)                   li_list = html.xpath("//div[@class='layout-Module-container layout-Cover ListContent']//li" )         content_list = []                  for  li in  li_list:             item = {}             item["img" ] = li.xpath(".//div[@class='LazyLoad is-visible']/img/@src" )                          item["title" ] = li.xpath(".//div[@class='DyListCover-content']/div[1]/h3/text()" )                          item["category" ] = li.xpath(".//div[@class='DyListCover-content']/div[1]/span/text()" )                           item["author" ] = li.xpath(".//div[@class='DyListCover-content']/div[2]/h2/text()" )                          item["hot" ] = li.xpath(".//div[@class='DyListCover-content']/div[2]/span/text()" )                          print (item)             content_list.append(item)                                             return  content_list     def  save_content_list (self,content_list ):         for  content in  content_list:             with  open ("douyu.txt" ,"a" ,encoding="utf8" ) as  f:                 f.write(json.dumps(content,ensure_ascii=False ,indent=2 ))                  f.write("\n" )      def  run (self ):                           self.driver.get(self.strat_url)                  content_list = self.get_content_list()                  self.save_content_list(content_list)         self.driver.quit()  if  __name__ == '__main__' :     douyu = DouyuSpider()     douyu.run() 
其他 用pycharm安装lxml模块始终不成功,不晓得是什么原因。div[1]表示第一个div标签,div[last()]表示最后一个div标签。