Python 网络爬虫伪装成浏览器访问
普通的爬一个网页只需要3部就能搞定
1
2
3
4
5
6
7
8
9 1url = r'http://blog.csdn.net/jinzhichaoshuiping/article/details/43372839'
2
3sock = urllib.urlopen(url)
4
5html = sock.read()
6
7sock.close()
8
9
得到的
html
是字符类型的
,
可以输出打印
,
也可以保存进文档
.
f = file('CSDN.html', 'w')
f.write(html)
f.close()
但也有搞不定的时候
,
比如去爬
CSDN
的博客
,
会得到
403 Forbidden.
这时候需要将爬虫伪装成浏览器对网页进行访问
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 1def openurl(self,url):
2 """
3 打开网页
4 """
5 cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
6 self.opener = urllib2.build_opener(cookie_support,urllib2.HTTPHandler)
7 urllib2.install_opener(self.opener)
8 user_agents = [
9 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
10 'Opera/9.25 (Windows NT 5.1; U; en)',
11 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
12 'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
13 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
14 'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
15 "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7",
16 "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 ",
17 ]
18
19 agent = random.choice(user_agents)
20 self.opener.addheaders = [("User-agent",agent),("Accept","*/*"),('Referer','http://www.google.com')]
21 try:
22 res = self.opener.open(url)
23 htmlSource = res.read()
24 res.close()
25 #print htmlSource
26 f = file('CSDN.html', 'w')
27 f.write(htmlSource)
28 f.close()
29 return htmlSource
30 except Exception,e:
31 self.speak(str(e)+url)
32 raise Exception
33 else:
34 return res
35