这个不算网络爬虫,只是简单的抓取360搜索的联想词汇,熟悉python的基本语法使用。
有一点体会很深刻,还是得多看python文档,虽然是全英文的,不可否认,那里有太多的BIF可以直接利用,方便~
由于python默认输入的中文编码是ascii的,没办法转换到utf-8,而我们在360上抓取的时候可接受的格式为utf-8,于是不得不想办法将输入的中文keywords转换成utf-8编码,才能被搜索引擎所识别。
一开始我使用
raw_input("输入搜索的关键字:").decode("ascii").encode("utf-8")
这样解释器就报错了
UnicodeDecodeError: 'ascii' codec can't decode byte 0xbf in position 0: ordinal not in range(128)
后来看到有人这样,将ascii换成gbk
raw_input("输入搜索的关键字:").decode("gbk").encode("utf-8")
这样就在正常了,当然输出结果时候我们还是得用utf-8来解码的~
# -*- coding: utf-8 -*-
#Name:getInfo.py
#Function:360搜索关键字采集
#@2013-09-03
import urllib2
import urllib
import re
#关键字获取
keyword = urllib.quote(raw_input("输入搜索的关键字:").decode("gbk").encode("utf-8"))
#url以及数据包头模拟
url = "http://sug.so.360.cn/suggest/word?callback=suggest_so&encodein=utf-8&encodeout=utf-8&word="+keyword
headers = {
"GET":url,
"Host":"sug.so.360.cn",
"Referer":"http://www.so.com/",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.62 Safari/537.36"
}
#模拟人工发http包
req = urllib2.Request(url)
for key in headers:
req.add_header(key,headers[key])
suggestion = urllib2.urlopen(req).read() #搜索引擎服务器提供联想扩展词汇
#输出所有联想到的关键字
exp = re.findall("\"(.*?)\"",suggestion) #非贪婪匹配尽可能少的词
for item in exp:
print item.decode("utf-8") #输出并对每个联想关键字以utf-8解码