【问题标题】:"soup.prettify()" gives just URL"soup.prettify()" 只给出 URL
【发布时间】:2015-06-19 01:21:49
【问题描述】:

我正在使用 Python3,BeautifulSoup4

当我在下面运行代码时,它只给出 url "www.google.com" 而不是 XML。 没找到怎么回事。

from bs4 import BeautifulSoup
import urllib


html = "www.google.com"

soup = BeautifulSoup(html)


print (soup.prettify())

【问题讨论】:

  • "www.google.com" 不是 HTML。使用urllib2 或requests 下载HTML。
  • 请再次阅读您遵循的教程/文档

标签: python python-3.x beautifulsoup


【解决方案1】:

您需要使用 urllib2 或类似的库来获取 HTML

import urllib2
html = urllib2.urlopen("www.google.com")

soup = BeautifulSoup(html)

print (soup.prettify())

编辑:作为说明我为什么建议使用 urllib2 的旁注。如果您阅读 urllib 文档,您会发现“Python 3 中删除了 urlopen() 函数以支持 urllib2.urlopen()。”鉴于您已经标记了 Python3,urllib2 可能是您的最佳选择。

【讨论】:

    猜你喜欢
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2021-11-15
    • 2012-08-10
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    相关资源
    最近更新 更多