我正试着用漂亮的汤给维基百科上的人过生日。例如,http://en.wikipedia.org/wiki/Ezra_Taft_Benson的生日是1899年8月4日。为了达到bday,我使用了以下代码:
bday = url.find("span", class_="bday")但是,它选择了bday作为另一个标记的一部分出现在html代码中的实例。即<span class="bday dtstart published updated">1985-11-10 </span>。
有没有办法只用bday匹配确切的类标签?
我希望问题是清楚的,因为目前我得到的bday是1985-11-10,这不是正确的日期。
发布于 2012-09-23 21:45:53
当BeautifulSoup的所有其他匹配方法都失败时,您可以使用一个带有单个参数(标记)的函数:
>>> url.find(lambda tag: tag.name == 'span' and tag.get('class', []) == ['bday'])
<span class="bday">1899-08-04</span>上面的代码搜索类属性是单个元素列表('bday')的span标记。
发布于 2012-09-24 23:46:43
我会这样做的:
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的值
发布于 2012-09-23 21:13:51
尝试在beautifulsoup解析器中使用lxml。下面查找只有bday类的<span>标记(在本页中只有一个):
>>> 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'https://stackoverflow.com/questions/12552211
复制相似问题