如何使用Nokogiri从图像标签中抓取文本



我需要从如下格式的图像标签列表中获取文本:

<img src="/images/TextImage.ashx?text=Richmond" style="border-width:0px;" class="">

当我在Nokogiri中输入XPath时,得到:

[#<Nokogiri::XML::Element:0x80513954 name="img" attributes=[#<Nokogiri::XML::Attr:0x805138dc name="src" value="/images/TextImage.ashx?text=Richmond">, #<Nokogiri::XML::Attr:0x805138b4 name="style" value="border-width:0px;">]>] 

我能告诉Nokogiri返回"Richmond"吗?我正在寻找一个方法,将返回文本后的某个字符串。如果没有办法只得到"里士满",我怎么让它返回值?

您可以使用像

这样的xpath表达式提取src属性
src = doc.at_xpath '//img/@src'

之后,您需要从属性中提取名称,可能使用regex。

例如(这可能需要更复杂,取决于HTML页面中src属性中可能的格式):

/?text=(.*)/ =~ src
puts $1

最新更新