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/