I need help with an lxml statement in python that extracts a meta-tag value
I need help fixing this lxml statement to extract the: http://www.etc../1tru.jpg link in the head section of http://www.yfrog.com/9d1truj
#This doe开发者_C百科sn't work!
# <link rel="image_src" href="http://img337.yfrog.com/img337/5023/1tru.jpg" />
def extract_imageurl(self, doc):
try:
self.url, = doc.xpath('//head//link[@rel="image_src"][1]/@href')
except ValueError:
self.url = "Error"
thanks
In [32]: doc.xpath('//head/link[@rel="image_src"]/@href')[0]
Out[32]: 'http://img337.yfrog.com/img337/5023/1tru.jpg'
Notice xpath
returns a list of nodes:
In [25]: doc.xpath('//head/link')
Out[25]: [<Element link at 9c94c5c>, <Element link at 9c94b6c>]
Once you've specified [@rel="image_src"]
there is only one node in the list.
You can pick off the node with [0]
after the xpath
call.
In [29]: doc.xpath('//head/link[@rel="image_src"]')[0]
Out[29]: <Element link at 9c94c5c>
import lxml.html as lh
import urllib2
url=r'http://www.yfrog.com/9d1truj'
doc=lh.parse(urllib2.urlopen(url))
link=doc.xpath('//head/link[@rel="image_src"]/@href')[0]
print(link)
# http://img337.yfrog.com/img337/5023/1tru.jpg
精彩评论