Scrapy中选择器的用法
官方文档:https://doc.scrapy.org/en/latest/topics/selectors.html
Using selectors
Constructing selectors
Response objects expose a Selector
instance on .selector
attribute:
>>> response.selector.xpath('//span/text()').get()
'good'
Querying responses using XPath and CSS is so common that responses include two more shortcuts: response.xpath()
and response.css()
:
>>> response.xpath('//span/text()').get()
'good'
>>> response.css('span::text').get()
'good'
Scrapy selectors are instances of Selector
class constructed by passing either TextResponse
object or markup as an unicode string (in text
argument). Usually there is no need to construct Scrapy selectors manually: response
object is available in Spider callbacks, so in most cases it is more convenient to use response.css()
and response.xpath()
shortcuts. By using response.selector
or one of these shortcuts you can also ensure the response body is parsed only once.
But if required, it is possible to use Selector
directly. Constructing from text:
>>> from scrapy.selector import Selector
>>> body = '<html><body><span>good</span></body></html>'
>>> Selector(text=body).xpath('//span/text()').get()
'good'
Constructing from response - HtmlResponse
is one ofTextResponse
subclasses:
>>> from scrapy.selector import Selector
>>> from scrapy.http import HtmlResponse
>>> response = HtmlResponse(url='http://example.com', body=body)
>>> Selector(response=response).xpath('//span/text()').get()
'good'
Selector
automatically chooses the best parsing rules (XML vs HTML) based on input type.
Using selectors
To explain how to use the selectors we’ll use the Scrapy shell (which provides interactive testing) and an example page located in the Scrapy documentation server:
For the sake of completeness, here’s its full HTML code:
<html>
<head>
<base href='http://example.com/' />
<title>Example website</title>
</head>
<body>
<div id='images'>
<a href='image1.html'>Name: My image 1 <br /><img src='image1_thumb.jpg' /></a>
<a href='image2.html'>Name: My image 2 <br /><img src='image2_thumb.jpg' /></a>
<a href='image3.html'>Name: My image 3 <br /><img src='image3_thumb.jpg' /></a>
<a href='image4.html'>Name: My image 4 <br /><img src='image4_thumb.jpg' /></a>
<a href='image5.html'>Name: My image 5 <br /><img src='image5_thumb.jpg' /></a>
</div>
</body>
</html>
First, let’s open the shell:
scrapy shell https://docs.scrapy.org/en/latest/_static/selectors-sample1.html
Then, after the shell loads, you’ll have the response available as response
shell variable, and its attached selector in response.selector
attribute.
Since we’re dealing with HTML, the selector will automatically use an HTML parser.
So, by looking at the HTML code of that page, let’s construct an XPath for selecting the text inside the title tag:
>>> response.xpath('//title/text()')
[<Selector xpath='//title/text()' data='Example website'>]
To actually extract the textual data, you must call the selector .get()
or .getall()
methods, as follows:
>>> response.xpath('//title/text()').getall()
['Example website']
>>> response.xpath('//title/text()').get()
'Example website'
.get()
always returns a single result; if there are several matches, content of a first match is returned; if there are no matches, None is returned. .getall()
returns a list with all results.
Notice that CSS selectors can select text or attribute nodes using CSS3 pseudo-elements:
>>> response.css('title::text').get()
'Example website'
As you can see, .xpath()
and .css()
methods return a SelectorList
instance, which is a list of new selectors. This API can be used for quickly selecting nested data:
>>> response.css('img').xpath('@src').getall()
['image1_thumb.jpg',
'image2_thumb.jpg',
'image3_thumb.jpg',
'image4_thumb.jpg',
'image5_thumb.jpg']
If you want to extract only the first matched element, you can call the selector .get()
(or its alias .extract_first()
commonly used in previous Scrapy versions):
>>> response.xpath('//div[@id="images"]/a/text()').get()
'Name: My image 1 '
It returns None
if no element was found:
>>> response.xpath('//div[@id="not-exists"]/text()').get() is None
True
A default return value can be provided as an argument, to be used instead of None
:
>>> response.xpath('//div[@id="not-exists"]/text()').get(default='not-found')
'not-found'
Instead of using e.g. '@src'
XPath it is possible to query for attributes using .attrib
property of a Selector
:
>>> [img.attrib['src'] for img in response.css('img')]
['image1_thumb.jpg',
'image2_thumb.jpg',
'image3_thumb.jpg',
'image4_thumb.jpg',
'image5_thumb.jpg']
As a shortcut, .attrib
is also available on SelectorList directly; it returns attributes for the first matching element:
>>> response.css('img').attrib['src']
'image1_thumb.jpg'
This is most useful when only a single result is expected, e.g. when selecting by id, or selecting unique elements on a web page:
>>> response.css('base').attrib['href']
'http://example.com/'
Now we’re going to get the base URL and some image links:
>>> response.xpath('//base/@href').get()
'http://example.com/' >>> response.css('base::attr(href)').get()
'http://example.com/' >>> response.css('base').attrib['href']
'http://example.com/' >>> response.xpath('//a[contains(@href, "image")]/@href').getall()
['image1.html',
'image2.html',
'image3.html',
'image4.html',
'image5.html'] >>> response.css('a[href*=image]::attr(href)').getall()
['image1.html',
'image2.html',
'image3.html',
'image4.html',
'image5.html'] >>> response.xpath('//a[contains(@href, "image")]/img/@src').getall()
['image1_thumb.jpg',
'image2_thumb.jpg',
'image3_thumb.jpg',
'image4_thumb.jpg',
'image5_thumb.jpg'] >>> response.css('a[href*=image] img::attr(src)').getall()
['image1_thumb.jpg',
'image2_thumb.jpg',
'image3_thumb.jpg',
'image4_thumb.jpg',
'image5_thumb.jpg']
Extensions to CSS Selectors
Per W3C standards, CSS selectors do not support selecting text nodes or attribute values. But selecting these is so essential in a web scraping context that Scrapy (parsel) implements a couple of non-standard pseudo-elements:
- to select text nodes, use
::text
- to select attribute values, use
::attr(name)
where name is the name of the attribute that you want the value of
Warning
These pseudo-elements are Scrapy-/Parsel-specific. They will most probably not work with other libraries like lxml or PyQuery.
Examples:
title::text
selects children text nodes of a descendant<title>
element:>>> response.css('title::text').get()
'Example website'*::text
selects all descendant text nodes of the current selector context:>>> response.css('#images *::text').getall()
['\n ',
'Name: My image 1 ',
'\n ',
'Name: My image 2 ',
'\n ',
'Name: My image 3 ',
'\n ',
'Name: My image 4 ',
'\n ',
'Name: My image 5 ',
'\n ']foo::text
returns no results iffoo
element exists, but contains no text (i.e. text is empty):>>> response.css('img::text').getall()
[]This means
.css('foo::text').get()
could return None even if an element exists. Usedefault=''
if you always want a string:>>> response.css('img::text').get()
>>> response.css('img::text').get(default='')
''a::attr(href)
selects the href attribute value of descendant links:>>> response.css('a::attr(href)').getall()
['image1.html',
'image2.html',
'image3.html',
'image4.html',
'image5.html']
Note
See also: Selecting element attributes.
Note
You cannot chain these pseudo-elements. But in practice it would not make much sense: text nodes do not have attributes, and attribute values are string values already and do not have children nodes.
Nesting selectors
The selection methods (.xpath()
or .css()
) return a list of selectors of the same type, so you can call the selection methods for those selectors too. Here’s an example:
>>> links = response.xpath('//a[contains(@href, "image")]')
>>> links.getall()
['<a href="image1.html">Name: My image 1 <br><img src="data:image1_thumb.jpg"></a>',
'<a href="image2.html">Name: My image 2 <br><img src="data:image2_thumb.jpg"></a>',
'<a href="image3.html">Name: My image 3 <br><img src="data:image3_thumb.jpg"></a>',
'<a href="image4.html">Name: My image 4 <br><img src="data:image4_thumb.jpg"></a>',
'<a href="image5.html">Name: My image 5 <br><img src="data:image5_thumb.jpg"></a>'] >>> for index, link in enumerate(links):
... args = (index, link.xpath('@href').get(), link.xpath('img/@src').get())
... print('Link number %d points to url %r and image %r' % args) Link number 0 points to url 'image1.html' and image 'image1_thumb.jpg'
Link number 1 points to url 'image2.html' and image 'image2_thumb.jpg'
Link number 2 points to url 'image3.html' and image 'image3_thumb.jpg'
Link number 3 points to url 'image4.html' and image 'image4_thumb.jpg'
Link number 4 points to url 'image5.html' and image 'image5_thumb.jpg'
Selecting element attributes
There are several ways to get a value of an attribute. First, one can use XPath syntax:
>>> response.xpath("//a/@href").getall()
['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html']
XPath syntax has a few advantages: it is a standard XPath feature, and @attributes
can be used in other parts of an XPath expression - e.g. it is possible to filter by attribute value.
Scrapy also provides an extension to CSS selectors (::attr(...)
) which allows to get attribute values:
>>> response.css('a::attr(href)').getall()
['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html']
In addition to that, there is a .attrib
property of Selector. You can use it if you prefer to lookup attributes in Python code, without using XPaths or CSS extensions:
>>> [a.attrib['href'] for a in response.css('a')]
['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html']
This property is also available on SelectorList; it returns a dictionary with attributes of a first matching element. It is convenient to use when a selector is expected to give a single result (e.g. when selecting by element ID, or when selecting an unique element on a page):
>>> response.css('base').attrib
{'href': 'http://example.com/'}
>>> response.css('base').attrib['href']
'http://example.com/'
.attrib
property of an empty SelectorList is empty:
>>> response.css('foo').attrib
{}
Using selectors with regular expressions
Selector
also has a .re()
method for extracting data using regular expressions. However, unlike using .xpath()
or .css()
methods, .re()
returns a list of unicode strings. So you can’t construct nested .re()
calls.
Here’s an example used to extract image names from the HTML code above:
>>> response.xpath('//a[contains(@href, "image")]/text()').re(r'Name:\s*(.*)')
['My image 1',
'My image 2',
'My image 3',
'My image 4',
'My image 5']
There’s an additional helper reciprocating .get()
(and its alias .extract_first()
) for .re()
, named .re_first()
. Use it to extract just the first matching string:
>>> response.xpath('//a[contains(@href, "image")]/text()').re_first(r'Name:\s*(.*)')
'My image 1'
extract() and extract_first()
If you’re a long-time Scrapy user, you’re probably familiar with .extract()
and .extract_first()
selector methods. Many blog posts and tutorials are using them as well. These methods are still supported by Scrapy, there are no plans to deprecate them.
However, Scrapy usage docs are now written using .get()
and .getall()
methods. We feel that these new methods result in a more concise and readable code.
The following examples show how these methods map to each other.
SelectorList.get()
is the same asSelectorList.extract_first()
:>>> response.css('a::attr(href)').get()
'image1.html'
>>> response.css('a::attr(href)').extract_first()
'image1.html'SelectorList.getall()
is the same asSelectorList.extract()
:>>> response.css('a::attr(href)').getall()
['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html']
>>> response.css('a::attr(href)').extract()
['image1.html', 'image2.html', 'image3.html', 'image4.html', 'image5.html']
Selector.get()
is the same asSelector.extract()
:>>> response.css('a::attr(href)')[0].get()
'image1.html'
>>> response.css('a::attr(href)')[0].extract()
'image1.html'
For consistency, there is also
Selector.getall()
, which returns a list:>>> response.css('a::attr(href)')[0].getall()
['image1.html']
So, the main difference is that output of .get()
and .getall()
methods is more predictable: .get()
always returns a single result, .getall()
always returns a list of all extracted results. With .extract()
method it was not always obvious if a result is a list or not; to get a single result either .extract()
or .extract_first()
should be called.
Working with XPaths
Here are some tips which may help you to use XPath with Scrapy selectors effectively. If you are not much familiar with XPath yet, you may want to take a look first at this XPath tutorial.
Note
Some of the tips are based on this post from ScrapingHub’s blog.
Working with relative XPaths
Keep in mind that if you are nesting selectors and use an XPath that starts with /
, that XPath will be absolute to the document and not relative to theSelector
you’re calling it from.
For example, suppose you want to extract all <p>
elements inside <div>
elements. First, you would get all <div>
elements:
>>> divs = response.xpath('//div')
At first, you may be tempted to use the following approach, which is wrong, as it actually extracts all <p>
elements from the document, not only those inside <div>
elements:
>>> for p in divs.xpath('//p'): # this is wrong - gets all <p> from the whole document
... print(p.get())
This is the proper way to do it (note the dot prefixing the .//p
XPath):
>>> for p in divs.xpath('.//p'): # extracts all <p> inside
... print(p.get())
Another common case would be to extract all direct <p>
children:
>>> for p in divs.xpath('p'):
... print(p.get())
For more details about relative XPaths see the Location Paths section in the XPath specification.
When querying by class, consider using CSS
Because an element can contain multiple CSS classes, the XPath way to select elements by class is the rather verbose:
*[contains(concat(' ', normalize-space(@class), ' '), ' someclass ')]
If you use @class='someclass'
you may end up missing elements that have other classes, and if you just use contains(@class, 'someclass')
to make up for that you may end up with more elements that you want, if they have a different class name that shares the string someclass
.
As it turns out, Scrapy selectors allow you to chain selectors, so most of the time you can just select by class using CSS and then switch to XPath when needed:
>>> from scrapy import Selector
>>> sel = Selector(text='<div class="hero shout"><time datetime="2014-07-23 19:00">Special date</time></div>')
>>> sel.css('.shout').xpath('./time/@datetime').getall()
['2014-07-23 19:00']
This is cleaner than using the verbose XPath trick shown above. Just remember to use the .
in the XPath expressions that will follow.
Beware of the difference between //node[1] and (//node)[1]
//node[1]
selects all the nodes occurring first under their respective parents.
(//node)[1]
selects all the nodes in the document, and then gets only the first of them.
Example:
>>> from scrapy import Selector
>>> sel = Selector(text="""
....: <ul class="list">
....: <li>1</li>
....: <li>2</li>
....: <li>3</li>
....: </ul>
....: <ul class="list">
....: <li>4</li>
....: <li>5</li>
....: <li>6</li>
....: </ul>""")
>>> xp = lambda x: sel.xpath(x).getall()
This gets all first <li>
elements under whatever it is its parent:
>>> xp("//li[1]")
['<li>1</li>', '<li>4</li>']
And this gets the first <li>
element in the whole document:
>>> xp("(//li)[1]")
['<li>1</li>']
This gets all first <li>
elements under an <ul>
parent:
>>> xp("//ul/li[1]")
['<li>1</li>', '<li>4</li>']
And this gets the first <li>
element under an <ul>
parent in the whole document:
>>> xp("(//ul/li)[1]")
['<li>1</li>']
Using text nodes in a condition
When you need to use the text content as argument to an XPath string function, avoid using .//text()
and use just .
instead.
This is because the expression .//text()
yields a collection of text elements – a node-set. And when a node-set is converted to a string, which happens when it is passed as argument to a string function like contains()
or starts-with()
, it results in the text for the first element only.
Example:
>>> from scrapy import Selector
>>> sel = Selector(text='<a href="#">Click here to go to the <strong>Next Page</strong></a>')
Converting a node-set to string:
>>> sel.xpath('//a//text()').getall() # take a peek at the node-set
['Click here to go to the ', 'Next Page']
>>> sel.xpath("string(//a[1]//text())").getall() # convert it to string
['Click here to go to the ']
A node converted to a string, however, puts together the text of itself plus of all its descendants:
>>> sel.xpath("//a[1]").getall() # select the first node
['<a href="#">Click here to go to the <strong>Next Page</strong></a>']
>>> sel.xpath("string(//a[1])").getall() # convert it to string
['Click here to go to the Next Page']
So, using the .//text()
node-set won’t select anything in this case:
>>> sel.xpath("//a[contains(.//text(), 'Next Page')]").getall()
[]
But using the .
to mean the node, works:
>>> sel.xpath("//a[contains(., 'Next Page')]").getall()
['<a href="#">Click here to go to the <strong>Next Page</strong></a>']
Variables in XPath expressions
XPath allows you to reference variables in your XPath expressions, using the $somevariable
syntax. This is somewhat similar to parameterized queries or prepared statements in the SQL world where you replace some arguments in your queries with placeholders like ?
, which are then substituted with values passed with the query.
Here’s an example to match an element based on its “id” attribute value, without hard-coding it (that was shown previously):
>>> # `$val` used in the expression, a `val` argument needs to be passed
>>> response.xpath('//div[@id=$val]/a/text()', val='images').get()
'Name: My image 1 '
Here’s another example, to find the “id” attribute of a <div>
tag containing five <a>
children (here we pass the value 5
as an integer):
>>> response.xpath('//div[count(a)=$cnt]/@id', cnt=5).get()
'images'
All variable references must have a binding value when calling .xpath()
(otherwise you’ll get a ValueError: XPath error:
exception). This is done by passing as many named arguments as necessary.
parsel, the library powering Scrapy selectors, has more details and examples on XPath variables.
Removing namespaces
When dealing with scraping projects, it is often quite convenient to get rid of namespaces altogether and just work with element names, to write more simple/convenient XPaths. You can use theSelector.remove_namespaces()
method for that.
Let’s show an example that illustrates this with the Python Insider blog atom feed.
First, we open the shell with the url we want to scrape:
$ scrapy shell https://feeds.feedburner.com/PythonInsider
This is how the file starts:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet ...
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/"
xmlns:blogger="http://schemas.google.com/blogger/2008"
xmlns:georss="http://www.georss.org/georss"
xmlns:gd="http://schemas.google.com/g/2005"
xmlns:thr="http://purl.org/syndication/thread/1.0"
xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">
...
You can see several namespace declarations including a default “http://www.w3.org/2005/Atom” and another one using the “gd:” prefix for “http://schemas.google.com/g/2005”.
Once in the shell we can try selecting all <link>
objects and see that it doesn’t work (because the Atom XML namespace is obfuscating those nodes):
>>> response.xpath("//link")
[]
But once we call the Selector.remove_namespaces()
method, all nodes can be accessed directly by their names:
>>> response.selector.remove_namespaces()
>>> response.xpath("//link")
[<Selector xpath='//link' data='<link rel="alternate" type="text/html" h'>,
<Selector xpath='//link' data='<link rel="next" type="application/atom+'>,
...
If you wonder why the namespace removal procedure isn’t always called by default instead of having to call it manually, this is because of two reasons, which, in order of relevance, are:
- Removing namespaces requires to iterate and modify all nodes in the document, which is a reasonably expensive operation to perform by default for all documents crawled by Scrapy
- There could be some cases where using namespaces is actually required, in case some element names clash between namespaces. These cases are very rare though.
Using EXSLT extensions
Being built atop lxml, Scrapy selectors support some EXSLT extensions and come with these pre-registered namespaces to use in XPath expressions:
prefix | namespace | usage |
---|---|---|
re | http://exslt.org/regular-expressions | regular expressions |
set | http://exslt.org/sets | set manipulation |
Regular expressions
The test()
function, for example, can prove quite useful when XPath’s starts-with()
or contains()
are not sufficient.
Example selecting links in list item with a “class” attribute ending with a digit:
>>> from scrapy import Selector
>>> doc = u"""
... <div>
... <ul>
... <li class="item-0"><a href="link1.html">first item</a></li>
... <li class="item-1"><a href="link2.html">second item</a></li>
... <li class="item-inactive"><a href="link3.html">third item</a></li>
... <li class="item-1"><a href="link4.html">fourth item</a></li>
... <li class="item-0"><a href="link5.html">fifth item</a></li>
... </ul>
... </div>
... """
>>> sel = Selector(text=doc, type="html")
>>> sel.xpath('//li//@href').getall()
['link1.html', 'link2.html', 'link3.html', 'link4.html', 'link5.html']
>>> sel.xpath('//li[re:test(@class, "item-\d$")]//@href').getall()
['link1.html', 'link2.html', 'link4.html', 'link5.html']
>>>
Warning
C library libxslt
doesn’t natively support EXSLT regular expressions so lxml’s implementation uses hooks to Python’s re
module. Thus, using regexp functions in your XPath expressions may add a small performance penalty.
Set operations
These can be handy for excluding parts of a document tree before extracting text elements for example.
Example extracting microdata (sample content taken from http://schema.org/Product) with groups of itemscopes and corresponding itemprops:
>>> doc = u"""
... <div itemscope itemtype="http://schema.org/Product">
... <span itemprop="name">Kenmore White 17" Microwave</span>
... <img src="kenmore-microwave-17in.jpg" alt='Kenmore 17" Microwave' />
... <div itemprop="aggregateRating"
... itemscope itemtype="http://schema.org/AggregateRating">
... Rated <span itemprop="ratingValue">3.5</span>/5
... based on <span itemprop="reviewCount">11</span> customer reviews
... </div>
...
... <div itemprop="offers" itemscope itemtype="http://schema.org/Offer">
... <span itemprop="price">$55.00</span>
... <link itemprop="availability" href="http://schema.org/InStock" />In stock
... </div>
...
... Product description:
... <span itemprop="description">0.7 cubic feet countertop microwave.
... Has six preset cooking categories and convenience features like
... Add-A-Minute and Child Lock.</span>
...
... Customer reviews:
...
... <div itemprop="review" itemscope itemtype="http://schema.org/Review">
... <span itemprop="name">Not a happy camper</span> -
... by <span itemprop="author">Ellie</span>,
... <meta itemprop="datePublished" content="2011-04-01">April 1, 2011
... <div itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating">
... <meta itemprop="worstRating" content = "1">
... <span itemprop="ratingValue">1</span>/
... <span itemprop="bestRating">5</span>stars
... </div>
... <span itemprop="description">The lamp burned out and now I have to replace
... it. </span>
... </div>
...
... <div itemprop="review" itemscope itemtype="http://schema.org/Review">
... <span itemprop="name">Value purchase</span> -
... by <span itemprop="author">Lucas</span>,
... <meta itemprop="datePublished" content="2011-03-25">March 25, 2011
... <div itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating">
... <meta itemprop="worstRating" content = "1"/>
... <span itemprop="ratingValue">4</span>/
... <span itemprop="bestRating">5</span>stars
... </div>
... <span itemprop="description">Great microwave for the price. It is small and
... fits in my apartment.</span>
... </div>
... ...
... </div>
... """
>>> sel = Selector(text=doc, type="html")
>>> for scope in sel.xpath('//div[@itemscope]'):
... print("current scope:", scope.xpath('@itemtype').getall())
... props = scope.xpath('''
... set:difference(./descendant::*/@itemprop,
... .//*[@itemscope]/*/@itemprop)''')
... print(" properties: %s" % (props.getall()))
... print("") current scope: ['http://schema.org/Product']
properties: ['name', 'aggregateRating', 'offers', 'description', 'review', 'review'] current scope: ['http://schema.org/AggregateRating']
properties: ['ratingValue', 'reviewCount'] current scope: ['http://schema.org/Offer']
properties: ['price', 'availability'] current scope: ['http://schema.org/Review']
properties: ['name', 'author', 'datePublished', 'reviewRating', 'description'] current scope: ['http://schema.org/Rating']
properties: ['worstRating', 'ratingValue', 'bestRating'] current scope: ['http://schema.org/Review']
properties: ['name', 'author', 'datePublished', 'reviewRating', 'description'] current scope: ['http://schema.org/Rating']
properties: ['worstRating', 'ratingValue', 'bestRating'] >>>
Here we first iterate over itemscope
elements, and for each one, we look for all itemprops
elements and exclude those that are themselves inside another itemscope
.
Other XPath extensions
Scrapy selectors also provide a sorely missed XPath extension function has-class
that returns True
for nodes that have all of the specified HTML classes.
For the following HTML:
<p class="foo bar-baz">First</p>
<p class="foo">Second</p>
<p class="bar">Third</p>
<p>Fourth</p>
You can use it like this:
>>> response.xpath('//p[has-class("foo")]')
[<Selector xpath='//p[has-class("foo")]' data='<p class="foo bar-baz">First</p>'>,
<Selector xpath='//p[has-class("foo")]' data='<p class="foo">Second</p>'>]
>>> response.xpath('//p[has-class("foo", "bar-baz")]')
[<Selector xpath='//p[has-class("foo", "bar-baz")]' data='<p class="foo bar-baz">First</p>'>]
>>> response.xpath('//p[has-class("foo", "bar")]')
[]
So XPath //p[has-class("foo", "bar-baz")]
is roughly equivalent to CSS p.foo.bar-baz
. Please note, that it is slower in most of the cases, because it’s a pure-Python function that’s invoked for every node in question whereas the CSS lookup is translated into XPath and thus runs more efficiently, so performance-wise its uses are limited to situations that are not easily described with CSS selectors.
Parsel also simplifies adding your own XPath extensions.
parsel.xpathfuncs.
set_xpathfunc
(fname, func)-
Register a custom extension function to use in XPath expressions.
The function
func
registered underfname
identifier will be called for every matching node, being passed acontext
parameter as well as any parameters passed from the corresponding XPath expression.If
func
isNone
, the extension function will be removed.See more in lxml documentation.
Built-in Selectors reference
Selector objects
- class
scrapy.selector.
Selector
(response=None, text=None, type=None, root=None, _root=None, **kwargs) -
An instance of
Selector
is a wrapper over response to select certain parts of its content.response
is anHtmlResponse
or anXmlResponse
object that will be used for selecting and extracting data.text
is a unicode string or utf-8 encoded text for cases when aresponse
isn’t available. Usingtext
andresponse
together is undefined behavior.type
defines the selector type, it can be"html"
,"xml"
orNone
(default).If
type
isNone
, the selector automatically chooses the best type based onresponse
type (see below), or defaults to"html"
in case it is used together withtext
.If
type
isNone
and aresponse
is passed, the selector type is inferred from the response type as follows:"html"
forHtmlResponse
type"xml"
forXmlResponse
type"html"
for anything else
Otherwise, if
type
is set, the selector type will be forced and no detection will occur.xpath
(query, namespaces=None, **kwargs)-
Find nodes matching the xpath
query
and return the result as aSelectorList
instance with all elements flattened. List elements implementSelector
interface too.query
is a string containing the XPATH query to apply.namespaces
is an optionalprefix: namespace-uri
mapping (dict) for additional prefixes to those registered withregister_namespace(prefix, uri)
. Contrary toregister_namespace()
, these prefixes are not saved for future calls.Any additional named arguments can be used to pass values for XPath variables in the XPath expression, e.g.:
selector.xpath('//a[href=$url]', url="http://www.example.com")
Note
For convenience, this method can be called as
response.xpath()
css
(query)-
Apply the given CSS selector and return a
SelectorList
instance.query
is a string containing the CSS selector to apply.In the background, CSS queries are translated into XPath queries using cssselect library and run
.xpath()
method.Note
For convenience, this method can be called as
response.css()
get
()-
Serialize and return the matched nodes in a single unicode string. Percent encoded content is unquoted.
See also: extract() and extract_first()
attrib
-
Return the attributes dictionary for underlying element.
See also: Selecting element attributes.
re
(regex, replace_entities=True)-
Apply the given regex and return a list of unicode strings with the matches.
regex
can be either a compiled regular expression or a string which will be compiled to a regular expression usingre.compile(regex)
.By default, character entity references are replaced by their corresponding character (except for
&
and<
). Passingreplace_entities
asFalse
switches off these replacements.
re_first
(regex, default=None, replace_entities=True)-
Apply the given regex and return the first unicode string which matches. If there is no match, return the default value (
None
if the argument is not provided).By default, character entity references are replaced by their corresponding character (except for
&
and<
). Passingreplace_entities
asFalse
switches off these replacements.
register_namespace
(prefix, uri)-
Register the given namespace to be used in this
Selector
. Without registering namespaces you can’t select or extract data from non-standard namespaces. See Selector examples on XML response.
remove_namespaces
()-
Remove all namespaces, allowing to traverse the document using namespace-less xpaths. See Removing namespaces.
__bool__
()-
Return
True
if there is any real content selected orFalse
otherwise. In other words, the boolean value of aSelector
is given by the contents it selects.
getall
()-
Serialize and return the matched node in a 1-element list of unicode strings.
This method is added to Selector for consistency; it is more useful with SelectorList. See also: extract() and extract_first()
SelectorList objects
- class
scrapy.selector.
SelectorList
-
The
SelectorList
class is a subclass of the builtinlist
class, which provides a few additional methods.xpath
(xpath, namespaces=None, **kwargs)-
Call the
.xpath()
method for each element in this list and return their results flattened as anotherSelectorList
.query
is the same argument as the one inSelector.xpath()
namespaces
is an optionalprefix: namespace-uri
mapping (dict) for additional prefixes to those registered withregister_namespace(prefix, uri)
. Contrary toregister_namespace()
, these prefixes are not saved for future calls.Any additional named arguments can be used to pass values for XPath variables in the XPath expression, e.g.:
selector.xpath('//a[href=$url]', url="http://www.example.com")
css
(query)-
Call the
.css()
method for each element in this list and return their results flattened as anotherSelectorList
.query
is the same argument as the one inSelector.css()
getall
()-
Call the
.get()
method for each element is this list and return their results flattened, as a list of unicode strings.See also: extract() and extract_first()
get
(default=None)-
Return the result of
.get()
for the first element in this list. If the list is empty, return the default value.See also: extract() and extract_first()
re
(regex, replace_entities=True)-
Call the
.re()
method for each element in this list and return their results flattened, as a list of unicode strings.By default, character entity references are replaced by their corresponding character (except for
&
and<
. Passingreplace_entities
asFalse
switches off these replacements.
re_first
(regex, default=None, replace_entities=True)-
Call the
.re()
method for the first element in this list and return the result in an unicode string. If the list is empty or the regex doesn’t match anything, return the default value (None
if the argument is not provided).By default, character entity references are replaced by their corresponding character (except for
&
and<
. Passingreplace_entities
asFalse
switches off these replacements.
attrib
-
Return the attributes dictionary for the first element. If the list is empty, return an empty dict.
See also: Selecting element attributes.
Examples
Selector examples on HTML response
Here are some Selector
examples to illustrate several concepts. In all cases, we assume there is already a Selector
instantiated with a HtmlResponse
object like this:
sel = Selector(html_response)
Select all
<h1>
elements from an HTML response body, returning a list ofSelector
objects (ie. aSelectorList
object):sel.xpath("//h1")
Extract the text of all
<h1>
elements from an HTML response body, returning a list of unicode strings:sel.xpath("//h1").getall() # this includes the h1 tag
sel.xpath("//h1/text()").getall() # this excludes the h1 tagIterate over all
<p>
tags and print their class attribute:for node in sel.xpath("//p"):
print(node.attrib['class'])
Selector examples on XML response
Here are some examples to illustrate concepts for Selector
objects instantiated with an XmlResponse
object:
sel = Selector(xml_response)
Select all
<product>
elements from an XML response body, returning a list ofSelector
objects (ie. aSelectorList
object):sel.xpath("//product")
Extract all prices from a Google Base XML feedwhich requires registering a namespace:
sel.register_namespace("g", "http://base.google.com/ns/1.0")
sel.xpath("//g:price").getall()
Scrapy中选择器的用法的更多相关文章
- Scrapy框架中选择器的用法【转】
Python爬虫从入门到放弃(十四)之 Scrapy框架中选择器的用法 请给作者点赞 --> 原文链接 Scrapy提取数据有自己的一套机制,被称作选择器(selectors),通过特定的Xpa ...
- scrapy框架中选择器的用法
scrapy框架中选择器的用法 Scrapy提取数据有自己的一套机制,被称作选择器(selectors),通过特定的Xpath或者CSS表达式来选择HTML文件的某个部分Xpath是专门在XML文件中 ...
- scrapy中选择器用法
一.Selector选择器介绍 python从网页中提取数据常用以下两种方法: lxml:基于ElementTree的XML解析库(也可以解析HTML),不是python的标准库 BeautifulS ...
- Python爬虫从入门到放弃(十四)之 Scrapy框架中选择器的用法
Scrapy提取数据有自己的一套机制,被称作选择器(selectors),通过特定的Xpath或者CSS表达式来选择HTML文件的某个部分Xpath是专门在XML文件中选择节点的语言,也可以用在HTM ...
- Python之爬虫(十六) Scrapy框架中选择器的用法
Scrapy提取数据有自己的一套机制,被称作选择器(selectors),通过特定的Xpath或者CSS表达式来选择HTML文件的某个部分Xpath是专门在XML文件中选择节点的语言,也可以用在HTM ...
- 三、Scrapy中选择器用法
官方示例源码<html> <head> <base href='http://example.com/' /> <title>Example web ...
- 4-----Scrapy框架中选择器的用法
Scrapy提取数据有自己的一套机制,被称作选择器(selectors),通过特定的Xpath或者CSS表达式来选择HTML文件的某个部分Xpath是专门在XML文件中选择节点的语言,也可以用在HTM ...
- 爬虫(十三):scrapy中pipeline的用法
当Item 在Spider中被收集之后,就会被传递到Item Pipeline中进行处理 每个item pipeline组件是实现了简单的方法的python类,负责接收到item并通过它执行一些行为, ...
- 爬虫(十二):scrapy中spiders的用法
Spider类定义了如何爬去某个网站,包括爬取的动作以及如何从网页内容中提取结构化的数据,总的来说spider就是定义爬取的动作以及分析某个网页 工作流程分析 以初始的URL初始化Request,并设 ...
随机推荐
- #5 Python面向对象(四)
前言 本节将是Python面向对象的最后一篇博文了,这节将记录类的特殊方法.特殊成员方法.旧类和新类的不同,以及一些其他知识.Go! 一.类的特殊方法 Python有三种特殊方法:实例方法.静态方法. ...
- Valgrind简介
Valgrind是一款用于内存调试.内存泄漏检测以及性能分析的软件开发工具.
- 重写(override)和重载(overload)的区别
override(重写): 是进行基类中函数的重写,是面向对象的概念 重载(overload):是方法的名称相同,参数或参数类型不同,进行多次重载以适应不同的需要.overload 是面向对象的概念.
- Scrapy-Redis分布式爬虫常规操作
一.X-path 的常规用法1./是从根节点选取,有顺序2.//从当前节点选择文档中的节点,无顺序3..选取当前节点4...选取当前节点的父节点5.@选取属性6. //div[@class='docl ...
- Android项目刮刮奖详解(一)
前言 最近正在学鸿洋大大的刮刮奖,感觉学有所得,便是来写篇详解(尽管网上有很多了,不过毕竟是自己写的,自己以后方便复习),正文开始 目标 实现画板功能 思路 我们需要自定义View来实现画板功能,之后 ...
- Netty学习笔记(五) 使用Netty构建静态网页服务器
昨天在继续完善基于Netty构建的聊天室系统的过程中,发现了一个有意思的知识点,特此拿来做一个简单的静态网页服务器,好好的玩一玩Netty. 但是不管怎么说利用netty实现各种功能的流程都是类似的 ...
- Linux 中NFS服务器的搭建
serve端IP:192.168.2.128 客户端IP:192.168.2.131 server端配置: 1.安装nfs,rpcbind,可以参考Linux 中yum的配置来安装: yum inst ...
- C#字符串转二进制、二进制转字符串
最近公司要做一个操作日志的模块,如果将操作日志以字符串的形式存到后台数据库,非常浪费内存,不可取,特意写了字符串与二进制相互转换的函数. 1.字符串转二进制 private string String ...
- iOS 开发 nonatomic 和 atomic
nonatomic : 非原子属性 atomic : 原子属性 如果不写关键字 那么默认就是 原子属性 - 多线程写入属性时,保证同一时间只有一个线程能够执行写入操作 - 单(线程)写多(线程 ...
- 三机互ping(自己总结)
主机与虚拟机互ping设置: 点击VMware下的[编辑]--[虚拟网络编辑器]设置如下: 屏幕剪辑的捕获时间: 2016/5/21 13:10 屏幕剪辑的捕获时间: ...