bs4 string与text的区别

原链接:https://zhuanlan.zhihu.com/p/30911642

用python写爬虫时,BeautifulSoup真是解析html,快速获取所需数据的神器。

这个美味汤使唤起来,屡试不爽。

 

在用find()方法找到特定的tag后,想获取里面的文本,可以用.text属性或者.string属性。

在很多时候,两者的返回结果一致,但其实两者是有区别的。

.string的资料很多,.text的资料比较少。

 

遍寻中文世界没有满意的答案,直接google在stock overflow中找到了很满意的解答:

 

.string on a Tag type object returns a NavigableString type object. On the other hand, .textgets all the child strings and return concatenated using the given separator. Return type of .text is unicode object.

From the documentation, A NavigableString is just like a Python Unicode string, except that it also supports some of the features described in Navigating the tree and Searching the tree.

From the documentation on .string, we can see that, If the html is like this,

<td>Some Table Data</td>
<td></td>

Then, .string on the second td will return None. But .text will return and empty string which is a unicode type object.

For more convenience,

string
  • Convenience property of a tag to get the single string within this tag.
  • If the tag has a single string child then the return value is that string.
  • If the tag has no children or more than one child the return value is None
  • If this tag has one child tag return value is the 'string' attribute of the child tag, recursively.

And text

  • Get all the child strings and return concatenated using the given separator.

If the html is like this:

1、<td>some text</td> 
2、<td></td>
3 、<td><p>more text</p></td>
4、<td>even <p>more text</p></td>
 

.string on the four td will return,

1、some text
2、None
3、more text
4、None

.text will give result like this

1、some text

2、more text
3、even more text 

通过以上的举例,可以很清楚的发现,.find和.string之间的差异:

第一行,在指定标签td,没有子标签,且有文本时,两者的返回结果一致,都是文本

第二行,在指定标签td,没有子标签,且没有文本时,.string返回None,.text返回为空

第三行,在指定标签td,只有一个子标签时,且文本只出现在子标签之间时,两者返回结果一致,都返回子标签内的文本

第四行,最关键的区别,在指定标签td,有子标签,并且父标签td和子标签p各自包含一段文本时,两者的返回结果,存在很大的差异

.string返回为空,因为文本数>=2,string不知道获取哪一个

.text返回的是,两段文本的拼接。

### BeautifulSoup4 属性的使用解释 #### 解析器的选择 当创建 `BeautifulSoup` 对象时,解析库是一个重要的参数。不同的解析库可能会影响文档树结构以及处理速度[^1]。 ```python from bs4 import BeautifulSoup html_doc = "<html><head><title>The Dormouse's story</title></head>...</html>" soup = BeautifulSoup(html_doc, 'html.parser') # 使用 Python 自带 HTML 解析器 ``` #### Tag对象及其常用属性 - **name**: 获取标签名称。 ```python tag.name ``` - **attrs**: 返回字典形式存储的所有HTML/XML标签内的属性键值对[^2]。 ```python print(tag.attrs) {'class': ['sister'], 'id': 'link1'} ``` - **string/strings/text/get_text()**: 提取 NavigableString 或者迭代获取所有子节点字符串内容[^3]。 ```python for string in soup.strings: print(repr(string)) # 去除多余空白字符 print(soup.get_text(strip=True)) ``` #### 导航树形结构的方法 通过点号`.`操作符可以方便地访问直接子元素;而利用方括号`[]`则能读取特定索引位置上的孩子结点或者指定属性名来获得相应特性值[^4]。 ```python first_child = tag.contents[0] specific_attribute_value = tag['href'] ``` #### 查找方法概述 提供多种方式定位页面中的目标组件,包括但不限于: - find_all(name , attrs , recursive , text , limit , **kwargs): 搜索当前Tag下所有的子孙节点并返回列表集合; - find(): 类似于find_all(), 不过只匹配第一个符合条件的结果即停止搜索过程; - select(css_selector): 支持CSS选择表达式的查询语句[^5]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值