ProgramingTip

Python에서 jquery와 같은 HTML 구문 분석?

bestdevel 2020. 12. 4. 19:48
반응형

Python에서 jquery와 같은 HTML 구문 분석?


jQuery가 수행하는 것과 동일한 HTML 문서를 구문 분석 할 수있는 Python 라이브러리가 있습니까?

즉, CSS 선택기 구문을 사용하여 문서에서 임의의 노드 집합을 가져오고 내용을 읽을 수 있기 때문에 원합니다.

이전에 사용하는 것이 유일한 Python HTML 구문 분석 라이브러리는 BeautifulSoup이 괜찮지 만 jQuery 구문을 사용할 수있는 권한 구문 분석을 수행하는 것이 더 빠를 계속 생각합니다. : 디


BeautifulSoup 에 능통하면 libs soupselect추가 하면 됩니다.
BeautifulSoup의 CSS 선택기 확장입니다.

용법 :

>>> from BeautifulSoup import BeautifulSoup as Soup
>>> from soupselect import select
>>> import urllib
>>> soup = Soup(urllib.urlopen('http://slashdot.org/'))
>>> select(soup, 'div.title h3')
[<h3><span><a href='//science.slashdot.org/'>Science</a>:</span></h3>,
 <h3><a href='//slashdot.org/articles/07/02/28/0120220.shtml'>Star Trek</h3>,
..]


PyQuery를 고려하십시오.

http://packages.python.org/pyquery/

>>> from pyquery import PyQuery as pq
>>> from lxml import etree
>>> import urllib
>>> d = pq("<html></html>")
>>> d = pq(etree.fromstring("<html></html>"))
>>> d = pq(url='http://google.com/')
>>> d = pq(url='http://google.com/', opener=lambda url: urllib.urlopen(url).read())
>>> d = pq(filename=path_to_html_file)
>>> d("#hello")
[<p#hello.hello>]
>>> p = d("#hello")
>>> p.html()
'Hello world !'
>>> p.html("you know <a href='http://python.org/'>Python</a> rocks")
[<p#hello.hello>]
>>> p.html()
u'you know <a href="http://python.org/">Python</a> rocks'
>>> p.text()
'you know Python rocks'

LXML의 라이브러리가 지원하는 CSS 선택기 .

참고 URL : https://stackoverflow.com/questions/3051295/jquery-like-html-parsing-in-python

반응형