nikolayp
nikolayp

Reputation: 17949

How to parse url in <a alt="url attribute"">

I have html code on a site:

<a alt="Кроссовки adidas. Цвет черный. Категории: Женская обувь, Лучшие отзывы, Кеды, кроссовки, ботинки. Вид 3." 
class="enabledZoom MagicThumb-swap" href="http://img2.site.ru/big/120000/129102-3.jpg" rel="zoom-id:Azoom;zoom-width:450;zoom-height:598;zoom-distance:10;zoom-position:right;opacity:50;" 
rev="http://img2.site.ru/large/120000/129102-3.jpg" style="outline: 0px; " id="mt-1334303054133">
<img src="http://img2.site.ru/tm/120000/129102-3.jpg" class=""></a>

How to extract "http://img2.site.ru/large/120000/129102-3.jpg" with nokogiri gem?

P.S. Nokogiri is parsing element :

[#<Nokogiri::XML::Element:0x42c1ad8 name="a" attributes=[#<Nokogiri::XML::Attr:0x42c1a7e name="alt" value="Кроссовки adidas. Цвет черный. Категории: Женская обувь, Лучшие отзывы, Кеды, кроссовки, ботинки. Вид 1.">, #<Nokogiri::XML::Attr:0x42c1a74 name="class" value="enabledZoom">, #<Nokogiri::XML::Attr:0x42c1a6a name="href" value="http://img2.site.ru/big/120000/129102-1.jpg">, #<Nokogiri::XML::Attr:0x42c1a60 name="rel" value="zoom-id:Azoom;zoom-width:450;zoom-height:598;zoom-distance:10;zoom-position:right;opacity:50;">, #<Nokogiri::XML::Attr:0x42c1a4c name="rev" value="http://img2.site.ru/large/120000/129102-1.jpg">] children=[#<Nokogiri::XML::Element:0x42c0ee4 name="img" attributes=[#<Nokogiri::XML::Attr:0x42c0e94 name="src" value="http://img2.site.ru/tm/120000/129102-1.jpg">, #<Nokogiri::XML::Attr:0x42c0e8a name="class" value="current">]>]>]

Upvotes: 0

Views: 270

Answers (1)

the Tin Man
the Tin Man

Reputation: 160631

You can use the at method if you know the <img> tag you want is in the first <a> tag:

doc.at('a img')['src'] => "http://img2.site.ru/tm/120000/129102-3.jpg"

If it's not, then you'll need to isolate the <a> or the <img>. I'd probably go after the <a id="..."> using something like:

doc.at('a#mt-1334303054133 img')['src'] => "http://img2.site.ru/tm/120000/129102-3.jpg"

If there are multiple <a> or <img> tags then your sample isn't good enough and we'd need more information about the HTML you're receiving.

Upvotes: 1

Related Questions