代码之家  ›  专栏  ›  技术社区  ›  mystery man

通过文本而非标记查找beautiful soup中的项目

  •  0
  • mystery man  · 技术社区  · 8 年前

    所以我试着从他们的维基百科页面上抓取一些特定位置的区域。以坎布里亚为例( https://en.wikipedia.org/wiki/Cumbria )我可以通过获取信息框;

    url = 'https://en.wikipedia.org/wiki/Cumbria'
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'lxml')
    value = soup.find('table', {"class": "infobox geography vcard"}) \
                .find('tr', {"class":"mergedrow"}).text
    

    然而 infobox geography vcard 有多个 <tr class='mergerow'> 子集和每个子集内是一个 <th scope='row'> .

    这个 <th scope='row'> 我想要的是 <th scope="row">Area</th> 我想知道是否可以从 <th scope=“行”>面积(<)/th> 通过搜索“区域”而不是标签,因为在 infobox地理vcard

    1 回复  |  直到 8 年前
        1
  •  1
  •   DeepSpace    8 年前

    你可以搜索所有 th 具有 scope=row 直接地然后对它们进行迭代,看看哪些有 Area 作为文本,并使用 find_next_sibling 为了得到下一个兄弟姐妹(这将是 td 与您需要的数据)。

    注意,此表有2个 地区 条目,一个为“礼仪县”,一个为“非都市县”,不管这意味着什么;)。

    ths = soup.find_all('th', {'scope': 'row'})
    
    for th in ths:
        if th.text == 'Area':
            area = th.find_next_sibling().text
            print(area)
    
    #  6,768 km2 (2,613 sq mi)
    #  6,768 km2 (2,613 sq mi)