使用python BeautifulSoup进行HTML抓取

时间:2017-03-28 06:24:51

标签: python web-scraping beautifulsoup

我有以下HTML文件,我试图使用BeautifulSoup刮掉完整的句子,但无法得到它。目前我只得到突出显示的单词。我想要的输出应该是

  

天线助推器已停止发送信号文件,可能是用户网络问题或BOOSTER问题。

任何解决方案?

  </table>
  <!--Record Header End-->
  <span style="BACKGROUND-COLOR: #0000ff; color: #ffffff">
   Antenna
  </span>
  <span style="BACKGROUND-COLOR: #0000ff; color: #ffffff">
   booster
  </span>
  has stopped
  <span style="BACKGROUND-COLOR: #0000ff; color: #ffffff">
   sending
  </span>
  signal files ,possible user
  <span style="BACKGROUND-COLOR: #0000ff; color: #ffffff">
   network
  </span>
  <span style="BACKGROUND-COLOR: #ff0000">
   issue
  </span>
  or BOOSTER
  <span style="BACKGROUND-COLOR: #ff0000">
   issue
  </span>
  .
  <br>
   <br>
    <br>

以下是我的尝试:

issue_field = soup.find_all('span', {'style':'BACKGROUND-COLOR: #0000ff; color: #ffffff'}) 
issue_str = str(issue_field) 
Issue_corpora = [word.lower() for word in BeautifulSoup(issue_str,'html.parser').get_text().strip().sp‌​lit(',')]
print(Issue_corpora)

2 个答案:

答案 0 :(得分:0)

问题是元素之外还有文本。 关于SO的问题已经存在重复:Get text outside known element beautifulsoup

所以这是解决方案,可能需要一点点抛光。 (请注意,变量t包含html作为文本)

from bs4 import BeautifulSoup as bs
soup = bs(t)
text = ''
for span in soup.findAll('span'):
    text += getattr(span, 'text', '').strip() + ' '
    text += getattr(span, 'nextSibling', '').strip() + ' '

使用这种方法的结果是:

>>> In : text
>>> Out: u'Antenna  booster has stopped sending signal files ,possible user network  issue or BOOSTER issue . '

您可以使用单个空格替换doubled空格,或者在逗号之前删除空格,或者在循环遍历span元素时定义规则来处理它。

答案 1 :(得分:0)

from bs4 import BeautifulSoup
import re 

example = """your example""" 

soup = BeautifulSoup(example, "html.parser")

_text = ""
for span in soup.find_all('span', style=re.compile('BACKGROUND-COLOR:')):
    _text += "%s %s" % (span.get_text(strip=True), span.next_sibling.replace("\n", ""))

print (re.sub(" +"," ", _text))

最后使用re修剪额外的空格。

输出:

  

天线助推器已停止发送信号文件,可能的用户网络问题或BOOSTER问题。