-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathCrawlerBaidu.py
43 lines (35 loc) · 1005 Bytes
/
CrawlerBaidu.py
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
#coding=utf-8
import urllib
import urllib2
import re
from bs4 import BeautifulSoup as BS
baseUrl = 'http://www.baidu.com/s'
page = 1 #第几页
word = '穿戴设备' #搜索关键词
data = {'wd':word,'pn':str(page-1)+'0','tn':'baidurt','ie':'utf-8','bsst':'1'}
data = urllib.urlencode(data)
url = baseUrl+'?'+data
try:
request = urllib2.Request(url)
response = urllib2.urlopen(request)
except urllib2.HttpError,e:
print e.code
exit(0)
except urllib2.URLError,e:
print e.reason
exit(0)
html = response.read()
soup = BS(html)
td = soup.find_all(class_='f')
for t in td:
print t.h3.a.get_text()
print t.h3.a['href']
font_str = t.find_all('font',attrs={'size':'-1'})[0].get_text()
start = 0 #起始
realtime = t.find_all('div',attrs={'class':'realtime'})
if realtime:
realtime_str = realtime[0].get_text()
start = len(realtime_str)
print realtime_str
end = font_str.find('...')
print font_str[start:end+3],'\n'