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

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)

发表评论