python - 美丽汤 4 + python : string returns 'None'

标签 python parsing html-parsing beautifulsoup

我试图用 BeautifulSoup4 和 Python 2.7.6 解析一些 html,但字符串返回“None”。我试图解析的 HTML 是:

<div class="booker-booking">
    2&nbsp;rooms
    &#0183;
    USD&nbsp;0
    <!-- Commission: USD  -->
</div>

我的Python代码片段是:

 data = soup.find('div', class_='booker-booking').string

我还尝试了以下两种:

data = soup.find('div', class_='booker-booking').text
data = soup.find('div', class_='booker-booking').contents[0]

两者都返回:

u'\n\t\t2\xa0rooms \n\t\t\xb7\n\t\tUSD\xa00\n\t\t\n

我最终试图将第一行放入一个仅表示“2 Rooms”的变量中,将第三行放入另一个仅表示“USD 0”的变量中。

最佳答案

.string 返回 None,因为文本节点不是唯一的子节点(有注释)。

from bs4 import BeautifulSoup, Comment

soup = BeautifulSoup(html)
div = soup.find('div', 'booker-booking')
# remove comments
text = " ".join(div.find_all(text=lambda t: not isinstance(t, Comment)))
# -> u'\n    2\xa0rooms\n    \xb7\n    USD\xa00\n     \n'

要删除 Unicode 空白:

text = " ".join(text.split())
# -> u'2 rooms \xb7 USD 0'
print text
# -> 2 rooms · USD 0

获取最终变量:

var1, var2 = [s.strip() for s in text.split(u"\xb7")]
# -> u'2 rooms', u'USD 0'

关于python - 美丽汤 4 + python : string returns 'None' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20750852/

相关文章:

python - 如何在python中解析html标签层次结构?

php - 从解析的 HTML 表构建数组

java - 使用 JSoup 解析 HTML

python - 桌面(基于控制台)应用程序的 Facebook 身份验证

python - 遍历字符串列并对 Pandas 中的单元格值进行排序

java - 使用 JSONPath 迭代大型 JSON 数组

python - 将 JSON 数据导入为 CSV 格式

python - 使用 Python 将大型 CSV 文件导入 MySQL

Python抛出ValueError : is not in list although it's there in list

python - 只从这个元素中提取文本,而不是它的子元素