python爬虫beautifulsoup string抓取问题

图片描述

我要的是这个蓝色部分的内容,但是beautifulsoup里两个方法,一个.strings还有一个get_text()都不行,他们会把下面span里的string:Good Sister-in-lwa:Forbidden love这些都抓取。.string直接抓不到,因为这个方法无法判断该抓取哪个string。
所以我该怎么解决标签里内嵌标签的抓取字符串问题

阅读 6.6k
4 个回答

@洛克 的想法不錯,把不要的標籤淬出或是移除,再取字串:

>>> from bs4 import BeautifulSoup
>>> html = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
>>> soup = BeautifulSoup(html)
>>> a_tag = soup.a
>>> i_tag = soup.i.extract()
>>> a_tag.string
'I linked to '

或是像 @cloverstd 說的:

>>> from bs4 import BeautifulSoup
>>> html = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
>>> soup = BeautifulSoup(html)
>>> a_tag = soup.a
>>> list(a_tag.strings)
[u'I linked to ', u'example.com']
>>> list(a_tag.strings)[0]
'I linked to '
>>> a_tag.contents[0]
'I linked to '

總之方法很多,任意組合囉...


我回答過的問題: Python-QA

把下面标签先取出来,用bs4的函数删掉好象是remove()。
再取上面就行了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题