Joe*_*Joe 4 python beautifulsoup
我正在使用beautifulsoup从html字符串中提取图像和链接.这一切都很好,但是有些链接在链接内容中有一个标记,它会引发错误.
示例链接:
<a href="http://www.example.com"><strong>Link Text</strong></a>
Run Code Online (Sandbox Code Playgroud)
Python代码:
soup = BeautifulSoup(contents)
links = soup.findAll('a')
for link in links:
print link.contents # generates error
print str(link.contents) # outputs [Link Text]
Run Code Online (Sandbox Code Playgroud)
错误信息:
TypeError: sequence item 0: expected string, Tag found
Run Code Online (Sandbox Code Playgroud)
我真的不想在链接文本中循环遍历任何子标记,我只想返回原始内容,这可能与BS有关吗?
Mar*_*ers 11
要仅获取标记的文本内容,该element.get_text()方法允许您从当前元素中抓取(剥离)文本,包括标记:
print link.get_text(' ', strip=True)
Run Code Online (Sandbox Code Playgroud)
第一个参数是用来连接所有文本元素,并坐strip于True意味着所有的文本元素首先去除的开头和结尾的空白.在大多数情况下,这为您提供了整洁的处理文本.
您还可以使用.stripped_stringsiterable:
print u' '.join(link.stripped_strings)
Run Code Online (Sandbox Code Playgroud)
这基本上是相同的效果,但您可以选择首先处理或过滤剥离的字符串.
要获取内容,请在每个子项上使用str()或unicode():
print u''.join(unicode(item) for item in link)
Run Code Online (Sandbox Code Playgroud)
这将适用于所有Element和NavigableString包含的项目.