【问题标题】:Python - BeautifulSoup - Unable to extract Span ValuePython - BeautifulSoup - 无法提取跨度值
【发布时间】:2020-06-17 12:05:37
【问题描述】:

我有一个包含多个 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]是我需要的文字总会出现的位置。

我不确定如何检索我需要的跨度值。

请您帮忙。谢谢

【问题讨论】:

  • 如果你想要的标签没有这个类,为什么要搜索attrs={'class': 'html-tag'}?

标签: python xml beautifulsoup


【解决方案1】:

您可以通过&lt;div class="line"&gt;搜索,然后选择第二个&lt;span&gt;

例如:

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

【讨论】:

  • 完美!非常感谢,对 Python 还是很陌生 :)
猜你喜欢
  • 1970-01-01
  • 2021-10-05
  • 2022-06-27
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多