Python爬虫初次开发
这周四讲了正则表达式,晚上就开始摸索着写一个网络爬虫。这个爬虫的功能就是从指定的网页开始,爬取这个网页里所有的链接,然后进入这些链接继续爬取新的链接,不断继续这个过程,并保存下所有爬取到的链接。这个爬虫目前还没有什么实际用处,后续可以在此基础上开发搜索指定信息等功能。
这个Python程序将用到以下模块:urllib, re, time
urllib:用来调用 urlopen 函数打开链接
re:编译正则表达式
time:用于计时[可选]
以下是我的代码:
1#code by SteveHawk
2
3from urllib.request import urlopen
4import re
5import time
6fo=open("pc00_result.txt","w") #打开要用于储存链接的文本文档
7list=[] #储存所有的链接
8x=0 #爬过的链接次数
9connected=0 #成功连上的数量
10num=0 #上一次储存的最后一个链接的索引
11list.append(input("输入网址:"))
12xn=int(input("输入爬虫总次数:"))
13start=time.clock() #开始计时
14while x<=xn:
15 if x>=len(list): #次数超出总链接数量就结束
16 end=time.clock() #结束计时
17 print("爬虫结束...!")
18 print("本次爬虫共爬过{}个网站,爬得{}个链接".format(connected, len(list)-1))
19 print("共耗时{:.3f}s".format(end-start))
20 fo.writelines("爬虫结束...!\n")
21 fo.writelines("本次爬虫共爬过{}个网站,爬得{}个链接\n".format(connected, len(list)-1))
22 fo.writelines("共耗时{:.3f}s\n".format(end-start))
23 break
24 try:
25 print("No.{}".format(x))
26 fo.writelines("No.{}\n".format(x))
27 print("正在连接{}".format(list[x]))
28 fo.writelines("正在连接{}\n".format(list[x]))
29 temp=urlopen(list[x],timeout=10) #打开链接 10秒超时
30 temp=temp.read().decode("utf-8") #读取网页内容并以utf-8方式解码
31 print("已连接上{}".format(list[x]))
32 fo.writelines("已连接上{}\n".format(list[x]))
33 patten=re.compile(r'https?://[^\\\'"\.].+?[^\\\'"](?:/|com|org|net|cn|cc|tv)')
34 print("正在解析{}".format(list[x]))
35 fo.writelines("正在解析{}\n".format(list[x]))
36 temp0=re.findall(patten, temp) #在之前读取的内容里进行匹配
37 connected+=1 #成功连接数加一
38 for i in range(len(temp0)):
39 if temp0[i] not in list: #新链接储存起来
40 list.append(temp0[i])
41 for j in range(num,len(list)):
42 print(list[j]) #输出这次新获得的链接
43 fo.writelines(list[j])
44 fo.writelines("\n")
45 num=len(list)
46 print("\n")
47 fo.writelines("\n\n")
48 except:
49 print("{}连接或解析失败\n\n".format(list[x]))
50 fo.writelines("{}连接或解析失败\n\n\n".format(list[x]))
51 x+=1
52 else:
53 x+=1
54else:
55 end=time.clock()
56 print("爬虫结束...!")
57 print("本次爬虫共爬过{}个网站,爬得{}个链接".format(connected,len(list)-1))
58 print("共耗时{:.3f}s".format(end-start))
59 fo.writelines("\n")
60 fo.writelines("爬虫结束...!")
61 fo.writelines("\n")
62 fo.writelines("本次爬虫共爬过{}个网站,爬得{}个链接".format(connected,len(list)-1))
63 fo.writelines("\n")
64 fo.writelines("共耗时{:.3f}s".format(end-start))
这个爬虫的关键在于那个正则表达式:
1patten=re.compile(r'https?://[^\\\'"\.].+?[^\\\'"](?:/|com|org|net|cn|cc|tv)'
这句的意思是把那个正则表达式编译成正则表达式对象然后储存在 patten 变量里。
而核心的正则表达式: https?://[^\\\'"\.].+?[^\\\'"](?:/|com|org|net|cn|cc|tv)
是指匹配以 http
开头,可能有 s
(https),加上 ://
,以 /
、com
、org
、net
、cn
、cc
、tv
结尾的链接
中间的 [^\\\'"\.]
指 http(s)://
后面不能直接跟 \ ' " .
这四个符号
.+?
指非贪婪的匹配任何字符
[^\\\'"]
指在com等结尾之前不能出现 \ ' "
的符号
这个表达式花了我很大力气写出来,而且匹配仍会有一定的出错率,目前还不知道有什么解决办法。
以上。
#tech notes
本文总字数 1704
本文阅读量
本站访客量