python - Python - BeautifulSoup - 无法提取跨度值
问题描述
我有一个带有多个 Div 类/跨度类的 XML,我正在努力提取一个文本值。
<div class="line">
<span class="html-tag">
"This is a Heading that I dont want"
</span>
<span>This is the text I want</span>
到目前为止,我已经写了这个:
html = driver.page_source
soup = BeautifulSoup(html, "lxml")
spans = soup.find_all('span', attrs={'class': 'html-tag'})[29]
print(spans.text)
不幸的是,这只会打印出“这是我不想要的标题”值,例如
This is the heading I dont want
代码中的数字[29]
是我需要的文本将始终出现的位置。
我不确定如何检索我需要的跨度值。
请你帮忙。谢谢
解决方案
您可以搜索<div class="line">
,然后选择第二个<span>
。
例如:
txt = '''
# line 1
<div class="line">
<span class="html-tag">
"This is a Heading that I dont want"
</span>
<span>This is the text I dont want</span>
</div>
# line 2
<div class="line">
<span class="html-tag">
"This is a Heading that I dont want"
</span>
<span>This is the text I dont want</span>
</div>
# line 3
<div class="line">
<span class="html-tag">
"This is a Heading that I dont want"
</span>
<span>This is the text I want</span> <--- this is I want
</div>'''
soup = BeautifulSoup(txt, 'html.parser')
s = soup.select('div.line')[2].select('span')[1] # select 3rd line 2nd span
print(s.text)
印刷:
This is the text I want
推荐阅读
- java - 自动回复广播接收者收到的消息
- javascript - 只有一些 CSS 自定义属性有效,尽管所有属性都清楚地显示在 HTML 中并由检查器显示
- .net - 为什么我通过拉动 dotnet docker 映像得到 sha256 验证错误?
- windows - Makefile CMD 长路径限制
- office365 - 有人在 Office365 桌面应用程序上部署了 Outlook 加载项吗?
- c++ - 初始化 C++ 基类而不键入整个基类类型两次
- java - spring data, PagingAndSorting repository, Sort based on (nested) attribute value of class type
- react-native - 在android模拟器上反应本机调试器
- qmake - 使用 qmake 时编译器标志从何而来?
- swift - 实施 Like what's app story 进度圈