찾다
백엔드 개발파이썬 튜토리얼Python查询阿里巴巴关键字排名的方法

本文实例讲述了Python查询阿里巴巴关键字排名的方法。分享给大家供大家参考。具体如下:

这里使用python库urllib及pyquery基本东西的应用,实现阿里巴巴关键词排名的查询,其中涉及到urllib代理的设置,pyquery对html文档的解析

1. 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)

2. 根据输入的公司名及关键词列表,返回每个关键词的排名

def search_keywords_rank(keyword_company_name, keywords):
  def get_context(url):
    start=clock()
    html=curl.get_html_body(url)
    finish=clock()
    print url,(finish-start)
    d = pq(html)
    items = d("#J-items-content .ls-item")
    items_c = len(items)
    print items_c
    if items_c < 38:
      return get_context(url)
    return items, items_c
  result = OrderedDict()
  for keyword in keywords:
    for page_index in range(1,9):
      u = url % (re.sub('\s+', '_', keyword.strip()), page_index)
      items, items_c = get_context(u)
      b = False
      for item_index in range(0, items_c):
        e=items.eq(item_index).find('.title a')
        p_title = e.text()
        p_url = e.attr('href')
        e=items.eq(item_index).find('.cright h3 .dot-product')
        company_name = e.text()
        company_url = e.attr('href')
        if keyword_company_name in company_url:
          total_index = (page_index-1)*38 +item_index+1+(0 if page_index==1 else 5)
          print 'page %s, index %s, total index %s' % (page_index, item_index+1, total_index)
          b = True
          if keyword not in result:
            result[keyword] = (p_title, p_url, page_index, item_index+1, total_index, u)
          break
      if b:
        break
  return result

希望本文所述对大家的Python程序设计有所帮助。

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Apr 24, 2025 pm 03:53 PM

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Apr 24, 2025 pm 03:49 PM

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

파이썬의 맥락에서 '배열'및 '목록'을 정의하십시오.파이썬의 맥락에서 '배열'및 '목록'을 정의하십시오.Apr 24, 2025 pm 03:41 PM

Inpython, "목록", isaversatile, mutablesequencetatcanholdmixeddatattypes, whilean "array"isamorememory-efficed, homogeneouseceenceRequiringElements ofthesAmeType.1) ListSareIdeAldiversEdatastorageandmanipulationDuetoIrflexibrieth

파이썬 목록은 변이 가능합니까? 파이썬 어레이는 어떻습니까?파이썬 목록은 변이 가능합니까? 파이썬 어레이는 어떻습니까?Apr 24, 2025 pm 03:37 PM

PythonlistsAndarraysareBotheBotheBothebothable.1) ListSareflexibleandsupporterogenousDatabutarabestemory-efficient.2) Arraysaremorememory-efforhomogeneousdatabutlessverstile, CorrectTypecodeusagetoavoidercer가 필요합니다.

Python vs. C : 주요 차이점 이해Python vs. C : 주요 차이점 이해Apr 21, 2025 am 12:18 AM

Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.

Python vs. C : 프로젝트를 위해 어떤 언어를 선택해야합니까?Python vs. C : 프로젝트를 위해 어떤 언어를 선택해야합니까?Apr 21, 2025 am 12:17 AM

Python 또는 C를 선택하는 것은 프로젝트 요구 사항에 따라 다릅니다. 1) 빠른 개발, 데이터 처리 및 프로토 타입 설계가 필요한 경우 Python을 선택하십시오. 2) 고성능, 낮은 대기 시간 및 근접 하드웨어 제어가 필요한 경우 C를 선택하십시오.

파이썬 목표에 도달 : 매일 2 시간의 힘파이썬 목표에 도달 : 매일 2 시간의 힘Apr 20, 2025 am 12:21 AM

매일 2 시간의 파이썬 학습을 투자하면 프로그래밍 기술을 효과적으로 향상시킬 수 있습니다. 1. 새로운 지식 배우기 : 문서를 읽거나 자습서를 시청하십시오. 2. 연습 : 코드를 작성하고 완전한 연습을합니다. 3. 검토 : 배운 내용을 통합하십시오. 4. 프로젝트 실무 : 실제 프로젝트에서 배운 것을 적용하십시오. 이러한 구조화 된 학습 계획은 파이썬을 체계적으로 마스터하고 경력 목표를 달성하는 데 도움이 될 수 있습니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구