【问题标题】:Python BeautifulSoup extracting contents of font tagPython BeautifulSoup 提取字体标签的内容
【发布时间】:2015-02-22 20:44:40
【问题描述】:

大家好,我正在尝试使用 beautifulSoup 来获取字体标签的内容。在 html 页面中,我正在解析要从中获取文本的标签:

<font color="#000000">Text I want to extract</font>

我正在尝试使用另一个 stackOverFlow 问题 (how to extract text within font tag using beautifulsoup)

html = urlopen(str(BASE_URL)).read()
soup = BeautifulSoup(html, "lxml")
info=soup('font', color="#000000")

print str(info)

但打印语句只返回[]。 知道我做错了什么吗?

【问题讨论】:

  • html 是什么样的?也可以通过print(soup.find("font").text) 来获取文本
  • 您发布的代码运行良好,这意味着您下载的 HTML 要么根本不包含这样的标签,要么完全损坏,以致于生成的修复版本 lxml 消除了该标签。
  • html 对我来说似乎非常复杂。这是检查元素的屏幕截图:imgur.com/nZ0ZAQ1
  • @Pecans:你的浏览器服务不一定是urlopen() 加载的;服务器可以根据标头和 cookie 免费为您提供不同的内容。您的浏览器还可以使用 JavaScript 代码来更改页面并异步加载其他内容。使用inspect 将向您显示这些更改之后的页面。
  • @Pecans:换句话说,仅仅因为您在浏览器的检查中看到它并不意味着它在使用 Python 加载时确实存在。查看实际的页面源代码(查看源代码)并使用“网络”选项卡检查是否有任何异步请求。检查可能正在转换内容的 JavaScript 代码。

标签: python html beautifulsoup


【解决方案1】:

给你:

from bs4 import BeautifulSoup

html = """<font color="#000000">Text I want to extract</font>"""

soup = BeautifulSoup(html, 'html.parser')

result1 = soup.find('font').text  # not specifying the color attribute
result2 = soup.find('font', {'color':'#000000'}).text  # specifying the color attribute

print result1  # prints 'Text I want to extract'
print result2  # prints 'Text I want to extract'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多