improvements

Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
This commit is contained in:
2018-02-25 09:44:45 -05:00
parent 7e0530a9c8
commit fae210c8a2
2 changed files with 25 additions and 8 deletions
+5 -4
View File
@@ -45,7 +45,7 @@ Select an element with a jQuery selector.
.. code-block:: pycon
>>> about = r.html.find('#about')[0]
>>> about = r.html.find('#about', first=True)
Grab an element's text contents:
@@ -85,11 +85,11 @@ Render an Element as Markdown:
* [Getting Started](/about/gettingstarted/)
* [Help](/about/help/)
* [Python Brochure](http://brochure.getpython.info/)
Search for text on the page:
.. code-block:: pycon
>>> r.html.search('Python is a {} language')[0]
programming
@@ -97,6 +97,7 @@ More complex CSS Selector example:
>>> r = session.get('https://github.com/')
>>> sel = 'body > div.application-main > div.jumbotron.jumbotron-codelines > div > div > div.col-md-7.text-center.text-md-left > p'
>>> print(r.html.find(sel)[0].text)
GitHub is a development platform inspired by the way you work. From open source to business, you can host and review code, manage projects, and build software alongside millions of other developers.
+20 -4
View File
@@ -63,13 +63,21 @@ class Element:
"""HTML representation of the element."""
return etree.tostring(self.element).decode('utf-8').strip()
def find(self, selector):
def find(self, selector, first=False):
"""Given a jQuery selector, returns a list of element objects."""
def gen():
for found in self.pq(selector):
yield Element(found)
return [g for g in gen()]
c = [g for g in gen()]
if first:
try:
return c[0]
except IndexError:
return None
else:
return c
def xpath(self, selector):
"""Given an XPath selector, returns a list of element objects."""
@@ -96,13 +104,21 @@ class HTML:
def __repr__(self):
return "<HTML url={}>".format(repr(self.url))
def find(self, selector):
def find(self, selector, first=False):
"""Given a jQuery selector, returns a list of element objects."""
def gen():
for found in self.pq(selector):
yield Element(found)
return [g for g in gen()]
c = [g for g in gen()]
if first:
try:
return c[0]
except IndexError:
return None
else:
return c
def search(self, template):
"""Searches the page for the given parse template."""