【问题标题】:Find (Beautiful Soup) returns None in case the tag is only one如果标签只有一个,Find (Beautiful Soup) 返回 None
【发布时间】:2021-05-09 06:21:52
【问题描述】:

谁能帮助我理解这种现象?如果标签只有一个,'find' 将返回 None。 (我已经尝试过'lxml',但没有帮助)。这是我在 IDE 中所做和接收的部分内容:

>>> driver = webdriver.Chrome("D:\\Text documents\\for work\\English project\\chromedriver")
>>> driver.get('https://www.interactive-english.ru/uprazhneniya/408-conditionals-exercise/')
>>> content = driver.page_source
>>> soup = BeautifulSoup(content, 'lxml')
>>> FullList = soup.findAll(['ol', 'h4', 'h5']);
>>> htmlF = FullList[1]

>>> htmlF

<ol>
    <li>
        Perhaps one day a cat will follow you home.<br />
        What would you do...
    </li>
    <li>
        Perhaps one day somebody will ask you to sing your favourite song.<br />
        What would you do...
    </li>
    <li>
        Perhaps one day you will find a hidden treasure.<br />
        What would you do...
    </li>
    <li>
        Perhaps one day somebody will throw an egg at you.<br />
        What would you do...
    </li>
    <li>
        Perhaps one day your car will be stolen.<br />
        What would you do...
    </li>
</ol>
>>> print(htmlF.find('li'))
<li>Perhaps one day a cat will follow you home.<br/>What would you do...</li>
>>> print(htmlF.find('ol'))
None
>>> 

【问题讨论】:

  • 展示如何创建 htmlF。如果它是基于显示的 html 的汤对象,我无法将其复制为正常工作。
  • QHarr,谢谢你的回答。我已经编辑了我的问题。

标签: python html css python-3.x beautifulsoup


【解决方案1】:

什么时候做的

htmlF = FullList[1]

检索到的顶层是ol 标记。其中没有嵌套的ol,这就是为什么当你调用.find('ol')时你会得到None

您可以通过以下方式检查:

print(htmlF.name)  
>> 'ol'

你可以的

htmlF.find('li') 

例如,要获得第一个孩子,因为 li 是您将 htmlF 设置为的父 ol 中的孩子。

【讨论】:

    【解决方案2】:

    试试:

    soup = BeautifulSoup(content, 'html.parser')
    FullList = soup.findAll(['ol', 'h4', 'h5']);
    for fl in FullList:
        print(fl)
    

    它会为我找到所有元素。

    【讨论】:

    • 谢谢。是的,我在我的程序中做同样的事情,但我还必须检查 'ol' 是否在 fl 中。可能,我应该检查 'ol' 字符串是否在 str(fl) 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 2015-07-17
    • 2014-11-29
    • 2020-12-16
    相关资源
    最近更新 更多