Skip to main content
 首页 » 编程设计

python之BeautifulSoup : Accessing li> elements from ul> with no id

2025年05月04日14me-sa

我正试图从这个 Wikipedia page 中抓取过生日的人

这是现有的代码:

hdr = {'User-Agent': 'Mozilla/5.0'} 
site = "http://en.wikipedia.org/wiki/"+"january"+"_"+"1" 
req = urllib2.Request(site,headers=hdr)     
page = urllib2.urlopen(req) 
soup = BeautifulSoup(page) 
 
print soup 

一切正常,我得到了整个 HTML 页面,但我想要特定数据,但我不知道如何在没有 id 的情况下使用 Beautiful Soup 访问它。 <ul>标签没有 ID,<li> 也没有标签。另外,我不能只要求每个 <li>标记,因为页面上还有其他列表。有没有特定的方法来调用给定的列表? (我不能只对这一页使用修复程序,因为我计划遍历所有日期并获取每一页的生日,而且我不能保证每一页的布局都与这一页完全相同)。

请您参考如下方法:

想法是获取带有 Births id 的 span,找到 parent 的下一个 sibling (即 ul)并迭代它的 li 元素。这是一个使用 requests 的完整示例(尽管它不相关):

from bs4 import BeautifulSoup as Soup, Tag 
 
import requests 
 
 
response = requests.get("http://en.wikipedia.org/wiki/January_1") 
soup = Soup(response.content) 
 
births_span = soup.find("span", {"id": "Births"}) 
births_ul = births_span.parent.find_next_sibling() 
 
for item in births_ul.findAll('li'): 
    if isinstance(item, Tag): 
        print item.text 

打印:

871 – Zwentibold, Frankish son of Arnulf of Carinthia (d. 900) 
1431 – Pope Alexander VI (d. 1503) 
1449 – Lorenzo de' Medici, Italian politician (d. 1492) 
1467 – Sigismund I the Old, Polish king (d. 1548) 
1484 – Huldrych Zwingli, Swiss pastor and theologian (d. 1531) 
1511 – Henry, Duke of Cornwall (d. 1511) 
1516 – Margaret Leijonhufvud, Swedish wife of Gustav I of Sweden (d. 1551) 
... 

希望对您有所帮助。