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
|
#!/usr/bin/python3 import
os import
os.path import
urllib.request import
chardet import
time import
re from
multiprocessing.dummy import
Pool as ThreadPool def
url_content_read(url): res
=
urllib.request.urlopen(url).read() return
res def
url_socket_list_pharse(socket_raw_info_data): p
=
re. compile (r '<td>(\d+\.\d+\.\d+\.\d+)</td><td>(\d+)</td>' ) socket_info_list
=
p.findall(socket_raw_info_data) socket_pharsed_info_list
=
[] for
s_info in
socket_info_list: socket_pharsed_info_list.append( "%s:%s" % (s_info[ 0 ],s_info[ 1 ])) return
socket_pharsed_info_list if
__name__ = =
"__main__" : urls
=
[] for
i in
range ( 1 , 42 ): urls.append( "http://www.proxy.com.ru/list_%d.html" % (i)) start_time
=
time.time() _pool
=
ThreadPool( 4 ) results
=
_pool. map (url_content_read,urls) _pool.close() _pool.join() print ( "time
spent: %f" % (time.time()
-
start_time)) p
=
re. compile (r 'http://[\w|\d|-|\.]+[:\d+]*[/|\w|\d|\.|%|@|&|\*|\+|#|\?|\=|\-]+' ) #对获取的结果网页进行字符串的编码解码 socket_info_raw_data_list
=
[] for
res in
results: det_res
=
chardet.detect(res) #print(det_res) if
det_res[ 'encoding' ]
= =
'utf-8' : socket_info_raw_data_list.append(res.decode( 'utf-8' , 'ignore' )) elif
det_res[ 'encoding' ]
= =
'GB2312' : socket_info_raw_data_list.append(res.decode( 'GB2312' , 'ignore' )) else : socket_info_raw_data_list.append(res.decode( 'gbk' , 'ignore' )) #对结果进行进一步的解析 start_time
=
time.time() _pool
=
ThreadPool( 40 ) results
=
_pool. map (url_socket_list_pharse,socket_info_raw_data_list) _pool.close() _pool.join() print ( "time
spent: %f" % (time.time()
-
start_time)) #最后对结果进行输出 fp
=
open (r '/home/mobilefzb/socket_list.txt' , 'w' ) for
res in
results: for
si_res in
res: fp.write( "%s\n" % (si_res)) fp.close() |
|
主要爬取“http://www.proxy.com.ru”这个网站的代理服务器列表,然后将其整理成为如截图所示的格式(开源中国)。
我的python版本为2.7 在编译过程中遇到如题报错。
查询资料:
python中,每个py文件被称之为模块,每个具有__init__.py文件的目录被称为包。只要模块或者包所在的目录在sys.path中,就可以使用import 模块或import 包来使用。
如果想使用非当前模块中的代码,需要使用Import。如果你要使用的模块(py文件)和当前模块在同一目录,只要import相应的文件名就好,比如在a.py中使用b.py:
import b
但是如果要import一个不同目录的文件(例如b.py)该怎么做呢?
首先需要使用sys.path.append方法将b.py所在目录加入到搜素目录中。然后进行import即可,例如
import sys
sys.path.append('c:\xxxx\b.py')
问题答案:
urllib.request及urllib.error
3.0版本后又urllib2模块拆分而来,导致3.0使用此模块程序到2.0+版本无法正常使用,具体怎么解决还没实现,探索中、、、
参考:
https://docs.python.org/2/library/urllib2.html
http://tieba.baidu.com/p/2265012496