Programing

Python에서 가장 좋은 것은 urllib2, PycURL 또는 mechanize?

lottogame 2020. 10. 27. 07:47
반응형

Python에서 가장 좋은 것은 urllib2, PycURL 또는 mechanize?


좋아, 파이썬을 사용하여 웹 페이지를 다운로드하고 내 옵션을 빠르게 조사해야합니다.

Python에 포함 :

urllib- 대신 urllib2를 사용해야한다고 생각합니다. urllib에는 쿠키 지원이 없으며 HTTP / FTP / 로컬 파일 만 (SSL 없음)

urllib2- 완전한 HTTP / FTP 클라이언트, 쿠키와 같은 가장 필요한 것을 지원하고 모든 HTTP 동사를 지원하지 않음 (GET 및 POST 만, TRACE 없음 등)

전체 기능 :

mechanize -Firefox / IE 쿠키 사용 / 저장, 두 번째 링크 따르기 등의 작업 수행 가능, 적극적으로 유지 관리 (2011 년 3 월에 출시 된 0.2.5)

PycURL -curl이 수행하는 모든 작업 지원 (FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 및 LDAP), 나쁜 소식 : 2008 년 9 월 9 일 (7.19.0) 이후 업데이트되지 않음

새로운 가능성 :

urllib3- 연결 재사용 / 풀링 및 파일 게시 지원

더 이상 사용되지 않음 (대신 urllib / urllib2 사용) :

httplib -HTTP / HTTPS 만 (FTP 없음)

httplib2 -HTTP / HTTPS 전용 (FTP 없음)

나에게 가장 먼저 충격을주는 것은 urllib / urllib2 / PycURL / mechanize가 모두 잘 작동하는 꽤 성숙한 솔루션이라는 것입니다. mechanize 및 PycURL은 여러 Linux 배포판 (예 : Fedora 13) 및 BSD와 함께 제공되므로 설치는 일반적으로 문제가되지 않습니다 (좋습니다).

urllib2가 좋아 보이지만 PycURL과 mechanize가 둘 다 매우 인기있는 이유가 궁금합니다. 제가 놓친 부분이 있습니까 (예 : urllib2를 사용하면 어느 시점에서 구석에 자신을 칠할까요?). 나는 나 자신을 위해 최선의 선택을 할 수 있도록 이러한 것들의 장단점에 대한 피드백을 정말로 받고 싶습니다.

편집 : urllib2의 동사 지원에 대한 메모 추가


  • urllib2 모든 Python 설치에서 찾을 수 있으므로 시작하기에 좋은 기반입니다.
  • PycURL 이미 libcurl 사용에 익숙한 사람들에게 유용하고 HTTP의 낮은 수준의 세부 정보를 더 많이 노출하고 libcurl에 적용된 수정 사항이나 개선 사항을 얻습니다.
  • mechanize 브라우저처럼 지속적으로 연결을 구동하는 데 사용됩니다.

한 쪽이 다른 쪽보다 낫다는 문제가 아니라 작업에 적합한 도구를 선택하는 문제입니다.


나는이 강연 (pycon 2009에서)이 당신이 찾고있는 것에 대한 답을 가지고 있다고 생각합니다 (Asheesh Laroia는이 문제에 대해 많은 경험을 가지고 있습니다). 그리고 그는 대부분의 목록에서 좋은 점과 나쁜 점을 지적합니다.

PYCON 2009 일정에서 :

추출해야 할 데이터가있는 웹 사이트에 직면 해 있습니까? 웹 애플리케이션에 프로그래밍 방식으로 데이터를 입력 할 수 있다면, 심지어 봇의 상호 작용에 저항하도록 조정 된 애플리케이션에도 데이터를 입력 할 수 있다면 삶이 더 단순 해 질까요?

웹 스크래핑의 기본 사항에 대해 논의한 다음 다양한 방법과 가장 적용 가능한 위치에 대해 자세히 알아 봅니다.

다른 도구를 언제 적용해야하는지 이해하고 전자 프론티어 재단 프로젝트에서 선택한 화면 스크래핑을위한 "무거운 망치"에 대해 배우게됩니다.

참석자는 가능한 경우 노트북을 가져 와서 우리가 논의한 예를 시도하고 선택적으로 메모를해야합니다.

업데이트 : Asheesh Laroia가 파이 콘 2010에 대한 프레젠테이션을 업데이트했습니다.

  • PyCon 2010 : 웹 스크랩 : 예상하지 못한 웹 사이트 프로그래밍 전략

    * My motto: "The website is the API."
    * Choosing a parser: BeautifulSoup, lxml, HTMLParse, and html5lib.
    * Extracting information, even in the face of bad HTML: Regular expressions, BeautifulSoup, SAX, and XPath.
    * Automatic template reverse-engineering tools.
    * Submitting to forms.
    * Playing with XML-RPC
    * DO NOT BECOME AN EVIL COMMENT SPAMMER.
    * Countermeasures, and circumventing them:
          o IP address limits
          o Hidden form fields
          o User-agent detection
          o JavaScript
          o CAPTCHAs 
    * Plenty of full source code to working examples:
          o Submitting to forms for text-to-speech.
          o Downloading music from web stores.
          o Automating Firefox with Selenium RC to navigate a pure-JavaScript service. 
    * Q&A; and workshopping
    * Use your power for good, not evil. 
    

업데이트 2 :

PyCon US 2012-웹 스크래핑 : 예상치 못한 페이지에서 안정적이고 효율적으로 데이터를 가져옴

흥미로운 정보는 웹 페이지와 HTML 양식 뒤에 갇혀 있습니다. 이 자습서에서는 해당 페이지를 구문 분석하는 방법과 스크래핑을 더 빠르고 안정적으로 만드는 고급 기술을 적용해야하는 경우를 배웁니다. Twisted, gevent 등을 사용한 병렬 다운로드에 대해 다룰 것입니다. SSL 뒤의 사이트 분석 Selenium으로 JavaScript-y 사이트 구동 그리고> 일반적인 긁힘 방지 기술을 회피합니다.


Python requests is also a good candidate for HTTP stuff. It has a nicer api IMHO, an example http request from their offcial documentation:

>>> r = requests.get('https://api.github.com', auth=('user', 'pass'))
>>> r.status_code
204
>>> r.headers['content-type']
'application/json'
>>> r.content
...

To "get some webpages", use requests!

From http://docs.python-requests.org/en/latest/ :

Python’s standard urllib2 module provides most of the HTTP capabilities you need, but the API is thoroughly broken. It was built for a different time — and a different web. It requires an enormous amount of work (even method overrides) to perform the simplest of tasks.

Things shouldn’t be this way. Not in Python.

>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}

Don't worry about "last updated". HTTP hasn't changed much in the last few years ;)

urllib2 is best (as it's inbuilt), then switch to mechanize if you need cookies from Firefox. mechanize can be used as a drop-in replacement for urllib2 - they have similar methods etc. Using Firefox cookies means you can get things from sites (like say StackOverflow) using your personal login credentials. Just be responsible with your number of requests (or you'll get blocked).

PycURL is for people who need all the low level stuff in libcurl. I would try the other libraries first.


Urllib2 only supports HTTP GET and POST, there might be workarounds, but If your app depends on other HTTP verbs, you will probably prefer a different module.


Every python library that speaks HTTP has its own advantages.

Use the one that has the minimum amount of features necessary for a particular task.

Your list is missing at least urllib3 - a cool third party HTTP library which can reuse a HTTP connection, thus speeding up greatly the process of retrieving multiple URLs from the same site.


Take a look on Grab (http://grablib.org). It is a network library which provides two main interfaces: 1) Grab for creating network requests and parsing retrieved data 2) Spider for creating bulk site scrapers

Under the hood Grab uses pycurl and lxml but it is possible to use other network transports (for example, requests library). Requests transport is not well tested yet.

참고URL : https://stackoverflow.com/questions/2385855/which-is-best-in-python-urllib2-pycurl-or-mechanize

반응형