【问题标题】:How to skip the first element of a <ul> using BeautifulSoup (python)?如何使用 BeautifulSoup (python) 跳过 <ul> 的第一个元素?
【发布时间】:2018-11-04 22:42:40
【问题描述】:

我有一个 python 代码可以从网页中检索一些数据(网络抓取)。

它返回以下列表的代码的某些点:

<ul class="nav nav--stacked" id="designer-list">
    <li>
        <h2>
            <a class="text-uppercase bold router-link-active" href="/en-ca/cars_all">
                All Cars
            </a>
        </h2>
    </li>
    <li>
        <a href="/en-ca/cars/c1">
            <span>
                The car c1
            </span>
        </a>
    </li>
    <li>
        <a href="/en-ca/cars/c2">
            <span>
                The car c2
            </span>
        </a>
    </li>
</ul>

我正在使用BeautifulSoup,我只想检索每辆车及其名称的引用 (href)。 在此示例中,我想检索 (/en-ca/cars/c1)=>(The car c1) AND (/en-ca/cars/c2)=>(The car c2)。我想跳过第一个元素(所有汽车)。

我可以使用.find_all('li') 并跳过循环内的第一个元素。 我想知道是否有办法通过 BeautifulSoup 方法拒绝元素

【问题讨论】:

  • 一般情况下,你可以得到一个数组,通过将其设为[1:],使其从1开始计数。

标签: python beautifulsoup


【解决方案1】:

你可以这样做,虽然它不是通过 BeautifulSoup 方法

soup = BeautifulSoup(html, "html.parser")

content = soup.find_all('li')[1:]

【讨论】:

  • 这里不需要list()find_all 返回一个列表。所以,直接使用切片。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-08
  • 2015-10-25
  • 1970-01-01
  • 2019-07-19
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多