` elements inside `
` elements from the document, not only those inside `
from the whole document ... print(p.get()) ... ``` This is the proper way to do it (note the dot prefixing the `.//p` XPath): ```pycon >>> for p in divs.xpath(".//p"): # extracts all
inside ... print(p.get()) ... ``` Another common case would be to extract all direct `
` children: ```pycon >>> for p in divs.xpath("p"): ... print(p.get()) ... ``` For more details about relative XPaths see the [Location Paths](https://www.w3.org/TR/xpath-10/#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: ```pycon >>> from scrapy import Selector >>> sel = Selector( ... text='
' ... ) >>> 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: ```pycon >>> from scrapy import Selector >>> sel = Selector(text=""" ...
... Second
... ...Fourth
... ... ... """, ... encoding="utf-8", ... ) ``` You can use it like this: ```pycon >>> response.xpath('//p[has-class("foo")]') [` tags and print their class attribute:
```python
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:
```python
sel = Selector(xml_response)
```
1. Select all ` Color TV the price is $1200 Color TV the price is $1200 Color TV the price is $1200 Color TV the price is $1200