如果标签只有一个,Find(Beautiful Soup)将返回None

2024-09-21 01:13:05 发布

您现在位置:Python中文网/ 问答频道 /正文

有谁能帮我理解这个现象吗?”如果标记只有一个,则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
>>> 

Tags: brnoneyoudriverlifinddowhat
2条回答

你什么时候做的

htmlF = FullList[1]

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

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

print(htmlF.name)  
>> 'ol'

你能行

htmlF.find('li') 

例如,要获取第一个子元素作为li是您设置为htmlF的父元素ol中的子元素

尝试:

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

它为我找到了所有元素

相关问题 更多 >

    热门问题