刮取:如何在<abbr>标记中获取属性

2024-09-29 23:18:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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

但对我来说不起作用。我们将不胜感激


Tags: 标记divheretitle链接responsehtml页面
2条回答

你试过xpath吗

In [38]: from lxml import etree

In [39]: import urllib2

In [40]: html = etree.fromstring(urllib2.urlopen('http://www.insiderpages.com/b/3721895833/central-kia-of-irving-irving').read(), parser)

In [41]: html.xpath('//abbr')[0].xpath('./@title')
Out[41]: ['3']

Don't use regex to extract data from html.如果您有lxml,请使用它的power(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']

相关问题 更多 >

    热门问题