python urllib模块和pyquery实现阿里巴巴排名查询

[url=http://www.jbxue.com/jb/python/]python[/url]库urllib及pyquery基本东西的应用,实现阿里巴巴关键词排名的查询,其中涉及到urllib代理的设置,pyquery对html文档的解析。

urllib基础模块的应用,通过该类获取到url中的html文档信息,内部可以重写代理的获取方法。

代码:
class ProxyScrapy(object):
def __init__(self):
self.proxy_robot = ProxyRobot()
self.current_proxy = None
self.cookie = cookielib.CookieJar()

def __builder_proxy_cookie_opener(self):
cookie_handler = urllib2.HTTPCookieProcessor(self.cookie)
handlers = [cookie_handler]
if PROXY_ENABLE:
self.current_proxy = ip_port = self.proxy_robot.get_random_proxy()
proxy_handler = urllib2.ProxyHandler({'http': ip_port[7:]})
handlers.append(proxy_handler)

opener = urllib2.build_opener(*handlers)
urllib2.install_opener(opener)
return opener
def get_html_body(self,url):
opener = self.__builder_proxy_cookie_opener()
request=urllib2.Request(url)
#request.add_header("Accept-Encoding", "gzip,deflate,sdch")
#request.add_header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
#request.add_header("Cache-Control", "no-cache")
#request.add_header("Connection", "keep-alive")
try:
response = opener.open(request,timeout=2)
http_code = response.getcode()
if http_code == 200:
if PROXY_ENABLE:
self.proxy_robot.handle_success_proxy(self.current_proxy)
html = response.read()
return html
else:
if PROXY_ENABLE:
self.proxy_robot.handle_double_proxy(self.current_proxy)
return self.get_html_body(url)
except Exception as inst:
print inst,self.current_proxy
self.proxy_robot.handle_double_proxy(self.current_proxy)
return self.get_html_body(url)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值