51

I want to get the href value:

<span class="title">
  <a href="https://www.example.com"></a>
</span>

I tried this:

Link = Link1.css('span[class=title] a::text').extract()[0]

But I just get the text inside the <a>. How can I get the link inside the href?

1
  • Could you give more details on what you're using & the code you're trying to parse? Might wanna try a::@href or a::href to select the attribute. Commented Jan 17, 2014 at 9:19

3 Answers 3

81

What you're looking for is:

Link = Link1.css('span[class=title] a::attr(href)').extract()[0]

Since you're matching a span "class" attribute also, you can even write

Link = Link1.css('span.title a::attr(href)').extract()[0]

Please note that ::text pseudo element and ::attr(attributename) functional pseudo element are NOT standard CSS3 selectors. They're extensions to CSS selectors in Scrapy 0.20.


Edit (2017-07-20): starting from Scrapy 1.0, you can use .extract_first() instead of .extract()[0]

Link = Link1.css('span[class=title] a::attr(href)').extract_first()
Link = Link1.css('span.title a::attr(href)').extract_first()
Sign up to request clarification or add additional context in comments.

7 Comments

The "extract()[0]" looks bad, is it possible to extract a single value not a list?
There's this proposal: github.com/scrapy/scrapy/issues/568 (quite a lot of debate). With this PR: github.com/scrapy/scrapy/pull/624 . I personally would like to see .get() and .getall()
Where can I see all Scrapy's CSS extensions? Can't find it in the docs.
Scrapy's extensions are documented in Parsel docs (the selectors library): parsel.readthedocs.io/en/latest/…
you can simply use Link = Link1.css('span.title a::attr(href)').get()
|
8
Link = Link1.css('span.title a::attr(href)').extract_first()

you can get more infomation from this

Comments

0

This will do the job:

Link = Link1.css('span.title a::attr(href)').extract()

Link will have the value : https://www.example.com

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.