【问题标题】:Problem selecting values from option tags in BeautifulSoup从 BeautifulSoup 中的选项标签中选择值的问题
【发布时间】:2021-03-20 06:26:16
【问题描述】:

我正在从如下下拉菜单中抓取链接(前后有一堆东西)

                            <li class="selectyear">
                                <select id="years">
                                    
                                        <option selected="" value="/linkfor2020" "="">2020 Name
                                    
                                        <option value="/linkfor2010" "="">2010 Name
                                    
                                        <option value="/linkfor2009" "="">2009 Name
                                    
                                </select>
                                <button class="selectyear" aria-label="Choose Year">Go</button>                        
                            </li>

我的代码如下:

with open("data.html") as fp:
soup = BeautifulSoup(fp, "html.parser")
yearlist = soup.find("option",value=True)
for item in yearlist.find_all('option'):
    value=item.get('value')
    print value

但是,它没有获取 2020 链接。输出只是后两个。为什么第一个选项被忽略了?

【问题讨论】:

    标签: beautifulsoup


    【解决方案1】:

    此 HTML 格式不正确。选项标签应该有结束标签(&lt;/option&gt;),但这里没有。 BeautifulSoup 无论如何都会尝试解析它,但它是这样读取的:

    <li class="selectyear">
    <select id="years">
      <option "="" selected="" value="/linkfor2020">2020 Name
        <option "="" value="/linkfor2010">2010 Name
          <option "="" value="/linkfor2009">2009 Name</option>
        </option>
      </option>
    </select>
    <button aria-label="Choose Year" class="selectyear">Go</button>
    </li>
    

    换句话说,options 都是嵌套的。当您调用yearlist = soup.find('option') 时,它会找到第一个最外层的选项标记。当您调用yearlist.find_all('option') 时,它会搜索所有options 外部option 标记,不包括原始外部标记。这是期望的行为:我们正在搜索给定标签的子标签,因此我们不应该在结果中返回父标签。

    您只需执行soup.find_all('option') 即可获得所有三个options 的列表。或者,如果返回您不想要的其他 options,您可以改为使用 soup.find('select', id='years').find_all('option')

    【讨论】:

      猜你喜欢
      • 2022-01-08
      • 2019-09-23
      • 2019-04-27
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 2019-04-26
      • 2011-07-08
      • 1970-01-01
      相关资源
      最近更新 更多