属性类的多个值

2024-09-29 23:27:57 发布

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

我正在尝试使用beautifulsoup为来自维基百科的人获取生日。例如,http://en.wikipedia.org/wiki/Ezra_Taft_Benson的生日是1899年8月4日。为了访问bday,我使用以下代码:

bday = url.find("span", class_="bday")

但是,它会选取一个实例,其中bday作为另一个标记的一部分出现在html代码中。i、 e<span class="bday dtstart published updated">1985-11-10 </span>。在

有没有办法只与bday匹配确切的类标记?在

我希望问题是清楚的,因为目前我得到的bday是1985-11-10,这不是正确的日期。在


Tags: 代码标记orghttpurlwikiwikipediaclass
3条回答

当BeautifulGroup的所有其他匹配方法都失败时,您可以使用带单个参数(tag)的函数:

>>> url.find(lambda tag: tag.name == 'span' and tag.get('class', []) == ['bday'])
<span class="bday">1899-08-04</span>

上面搜索的是一个span标记,其class属性是单个元素的列表('bday')。在

我会这样做的:

import urllib
from BeautifulSoup import BeautifulSoup

url = 'http://en.wikipedia.org/wiki/Ezra_Taft_Benson'
file_pointer = urllib.urlopen(url)
html_object = BeautifulSoup(file_pointer)

bday = html_object('span',{'class':'bday'})[0].contents[0] 

这将返回1899-08-04作为bday的值

尝试将lxmlbeautifulsoup解析器一起使用。以下内容只找到<span>标记,其中只有bday类(在本页中只有一个):

>>> from lxml.html.soupparser import fromstring
>>> root = fromstring(open('Ezra_Taft_Benson'))
>>> span_bday_nodes = root.findall('.//span[@class="bday"]')
[<Element span at 0x1be9290>]
>>> span_bday_node[0].text
'1899-08-04'

相关问题 更多 >

    热门问题