python - 我通过 python BeautifulSoup 获得了结果集,但我不知道如何获取其中的 NavigableString

标签 python beautifulsoup

html_text = driver.page_source
soup = BeautifulSoup(html_text, "html.parser")
get_details = soup.find_all('li', attrs={"class":"news"})
# get_details is an aggregation of results fetched by BeautifulSoup find_all() method

结果集的一个实例如下:

<li class="news">blah blah blah what i want blah blah blah  <a href="/graphic/graphicInfoData/000002230030421305">View details</a></li>

我想要的是“blah blah blah 我想要的blah blah blah”,即BeautifulSoup 中所谓的Navigable 字符串。但我无法对列表使用 .string 属性,即使我使用 print(get_details[0].string),结果也是 None,为什么?

顺便说一句,作为比较,下面的代码可以工作!

print(get_details[0].a.string)
>>> print(get_details[0].li.string)
    Traceback (most recent call last):
    File "<pyshell#57>", line 1, in <module>
    print(get_details[0].li.string)
    AttributeError: 'NoneType' object has no attribute 'string'

任何想法都将受到高度赞赏!

最佳答案

使用.get_text()代替.string:

print(get_details[0].a.get_text())

输出:查看详细信息

print(get_details[0].get_text())

输出:blah blah blah 我想要什么blah blah blah 查看详细信息

请注意,get_details[0].get_text() 将获取 li 的所有文本。

以下只会获取第一部分:

get_details[0].contents[0].strip()

输出:blah blah blah 我想要什么blah blah blah

关于python - 我通过 python BeautifulSoup 获得了结果集,但我不知道如何获取其中的 NavigableString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65664238/

相关文章:

python - 以自动宽度打印到 CSV 文件

python - 这是解决子集和的更好方法吗?

python - 如何在 python 中修改 html 树?

excel - 从带有 <li> 标签的网站中抓取 html 数据

python - Beautifulsoup find_all 没有找到全部

python - 无法腌制 <class 'abc.class_name' > : attribute lookup class_name on abc failed

python - 只提取 2 个字符的单词 Pandas Series

python - 确定两个字符串是否最多相差 n 个字符

python - 网络抓取Python不获取结果

python - bs4 中 .find() 的正确语法是什么?