今天继续爬虫练习,今天来抓一下古诗文网上的唐诗三百首,并保存在文本文件中。
网页的地址是:http://so.gushiwen.org/gushi/tangshi.aspx
其实抓取的思路跟之前的都差不多,没有什么太新颖的东西,就当做一次联系了吧。唯一的不懂应该就是编程思路,今天用面向对象的方式来实现以下爬虫(有时间把之前的程序也改成面向对象的方式)
Python版本:3.5.3
用到的库有
1.requests:用来获取网页源代码
2.BeautifulSoup:用来解析网页,获得相关信息
首先获取网页的源代码,并解析网页。
| 1 2 3
 | def geturl(self):     html = requests.get(url=self.page_url)     return html.text
 | 
打开网页找到相应信息所在的位置
                
                
            
发现所有古诗都在’leftlei’的标签中,从中就可以获得所有古诗的题目,作者以及对应链接的信息。通过BeautifulSoup获取相应信息,并构造相应的url
| 1 2 3 4 5 6 7 8 9
 | soup = BeautifulSoup(html, "html.parser")         items = soup.find('div',class_='leftlei').find_all('span')         cont = 1         for item in items:             gushi_url = item.find('a')             if gushi_url != None:                 title = item.find('a').get_text()                 author = item.get_text()[len(title) + 1:-1]                 cont += 1
 | 
从中可以发现,在当前页面中可以找到古诗的题目和作者的信息,找到其中一首古诗的元素,可以找到相应的链接,如图:
                
                
            
构造对应古诗的url
然后打开对应的链接,从地址上可以发现,每一首古诗对应的网页是http://so.gushiwen.org再加上相应古诗的链接
                
                
            
构造对应的url
| 1
 | gushi_url = 'http://so.gushiwen.org'+gushi_url['href']
 | 
然后依然在对应的古诗网页中找到古诗内容所在的位置,发现古诗的内容都位于id为’cont’的标签中
                
                
            
获取相应网页,并从中找到古诗内容
| 1 2 3 4 5
 | def getgushi(self,gushiurl):     html = requests.get(url=gushiurl)     soup = BeautifulSoup(html.text, "html.parser")     gushi = soup.find('div', id='cont').get_text().replace('\n','')     return gushi
 | 
这样就得到了所有的信息,然后在将每一次得到的古诗信息存在一个txt文本中
| 1 2 3 4 5 6 7
 | def savetotxt(self,cont,title,author,gushi):     f = open('tangshi.txt','a')     f.write(str(cont)+'\n')     f.write(title+'\n')     f.write(author+'\n')     f.write(gushi+'\n\n')     f.close()
 | 
最后运行程序
| 1 2
 | gushi = gushiwen() gushi.getitem()
 | 
打开文件,发现唐诗三百首中的内容已经存在文本中了