python无法爬取阿里巴巴www.1688.com的数据

zouyu139576 2014-07-19 12:09:09
最近写了一个爬取阿里巴巴网站的数据,主要作用就是利用python向阿里巴巴提供搜索请求,代码如下:
def getpage_content(url):
try:
req_header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept':'text/html;q=0.9,*/*;q=0.8',
'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding':'GBK,utf-8;q=0.7,*;q=0.3',
'Connection':'close',
'Referer':None #注意如果依然不能抓取的话,这里可以设置抓取网站的host
}
req_timeout = 5
req = urllib2.Request(url,None,req_header)
resp = urllib2.urlopen(req,None,req_timeout)
page = resp.read()
return page
except Exception, e:
print e
print "fail to get web ,redownload"
time.sleep(5) # 休眠10秒
page=getpage_content(url)
return page
def main(keyword):
search_url_head= 'http://s.1688.com/selloffer/offer_search.htm?keywords='
search_url=search_url_head+urllib2.quote(keyword)+'&button_click=top&earseDirect=false&n=y'
page=getpage_content(search_url)
#test
main('袜子')
在这里,我知道什么地方出了问题,阿里巴巴会把产生的关键词编码和urllib2.quote函数产生的编码不一致,这个问题困扰了好久了,求助!
...全文
1729 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zouyu139576 2014-07-21
  • 打赏
  • 举报
回复
谢谢!可以用了,这个编码的问题困扰了好久了!
lsjfdjoijvtghu 2014-07-20
  • 打赏
  • 举报
回复
字符编码有问题吧 一般网页是gbk的 我喜欢utf-8编码,于是代码头部加一句申明 # ecoding = utf-8 然后 '袜子'.decode('utf-8').encode('gbk') 这样应该不会有编码问题了

37,718

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧