Skip to main content
 首页 » 编程设计

python之抓取 : How to fetch an attribute in a abbr> tag

2025年05月04日21luoye11

我正在使用 lxml 和 python 来抓取页面。该页面的链接是 HERE 。我现在面临的问题是如何获取标签中的属性。例如页面顶部的 3 颗金星,它们有一个 html

<abbr title="3" class="average rating large star3">★★★☆☆</abbr> 

这里我想获取标题,以便我知道这个位置获得了多少颗星。

我已经尝试过做一些事情,包括:

response = urllib.urlopen('http://www.insiderpages.com/b/3721895833/central-kia-of-irving-irving').read() 
mo = re.search(r'<div class="rating_box">.*?</div>', response) 
div = html.fromstring(mo.group(0)) 
title = div.find("abbr").attrib["title"] 
print title 

但对我不起作用。帮助将不胜感激。

请您参考如下方法:

Don't use regex to extract data from html.你有 lxml,使用它的力量 ( XPath )。

>>> import lxml.html as html 
>>> page = html.parse("http://www.insiderpages.com/b/3721895833/central-kia-of-irving-irving") 
>>> print page.xpath("//div[@class='rating_box']/abbr/@title") 
['3']