python爬虫(一)

        什么是网络爬虫?爬虫可以理解为一段按照一段规则抓取网络信息的程序,比如我们常用的搜索引擎就是网络爬虫。因为python写爬虫的效率比较高,所以很多爬虫都是使用python开发的。

        爬虫模拟浏览器自动对服务器交互,一般web浏览器发生的事情:打开浏览器,浏览器对服务器发送请求,服务器回应客户端,浏览器显示网页。我们可以通过代码模拟这个过程,比如下载一部小说,代码框架如下

 1 import requests
 2 import re
 3 
 4 url = 'http://www.jingcaiyuedu.com/book/15401.html'
 5 
 6 response = requests.get(url)
 7 response.encoding = 'utf-8'
 8 
 9 html = response.text
10 
11 title = re.findall(r'',html)[0]
12 
13 fb = open('%s.txt'%title,'w',encoding=''utf-8)
14 
15 download = re.findall(r'',html,re.S)[0]
16 chapter_info_list = re.findall(r'',download)
17 
18 for chapter_info in chapter_info_list:
19     chapter_url,chapter_title = chapter_info
20     chapter_url = ''
21 
22     chapter_content = chapter_content.replace(' ','')
23 
24     fb.write(chapter_title)
25     fb.write(chapter_content)
26     fb.write('/n')
27 
28     print(chapter_url)

          request模块,提供了能发送网络请求的方法get,post等。思路:首先获取这个url页面的代码给response,修改编码形式。再用findall方法,用正则表达式检索相应的字段,保存小说的标题、章节号、内容。最后清洗数据和储存。

猜你喜欢

转载自www.cnblogs.com/Kammuri/p/8992992.html
今日推荐