【问题标题】:Parse HTML with Python [duplicate]用 Python 解析 HTML [重复]
【发布时间】:2012-10-01 18:30:52
【问题描述】:

我想用 Python 创建一个函数来获取网站内容, 例如获取网站组织内容。

在代码中,组织是东京大学:

<tr class="odd">
  <th>Organization:</th>
  <td>University of Tokyo</td>
</tr>

我怎样才能在没有任何新安装的情况下直接获取网站内容,比如get http://www.ip-adress.com/ip_tracer/157.123.22.11

【问题讨论】:

  • @jesseslu 您需要下载文件吗?还是只解析和访问?
  • 嗯,你需要获取html文件:)
  • 我认为您在按照其他人的建议打开此网站时会遇到问题。添加了一个答案来做到这一点......

标签: python html


【解决方案1】:

我喜欢BeautifulSoup,它可以轻松访问 HTML 字符串中的数据。 实际的复杂性取决于 HTML 的形成方式。如果 HTML 使用 'id's 和 'class'es,这很容易。如果不是,你依赖于更静态的东西,比如“获取第一个 div,第二个列表项,...”,如果 HTML 的内容发生很大变化,这很糟糕。

要下载 HTML,我引用 BeautifulSoup 文档中的示例:

import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen("http://www.icc-ccs.org/prc/piracyreport.php")
soup = BeautifulSoup(page)
for incident in soup('td', width="90%"):
    where, linebreak, what = incident.contents[:3]
    print where.strip()
    print what.strip()
    print

【讨论】:

【解决方案2】:

使用BeautifulSoup:

import bs4

html = """<tr class="odd">
  <th>Organization:</th>
  <td>University of Tokyo</td>
</tr>
"""
soup = bs4.BeautifulSoup(html)
univ = soup.tr.td.getText()
assert univ == u"University of Tokyo"

编辑:

如果您需要先阅读 HTML,请使用urllib2

import urllib2

html = urllib2.urlopen("http://example.com/").read()

【讨论】:

  • 如何在没有任何新安装的情况下直接获取网站内容,如get ip-adress.com/ip_tracer/157.123.22.11
  • 查看我的编辑以了解如何阅读内容。
  • 不要使用urllib2!请改用requests
  • @egasimus Requests 很好,但它不是 Python 标准库的一部分。
【解决方案3】:

您将使用urllib2.urlopen 获得403 Access Forbidden error,因为该网站正在通过检查是否被认可的用户代理访问来过滤访问。所以这是完整的事情:

import urllib2
import lxml.html as lh

req = urllib2.Request("http://www.ip-adress.com/ip_tracer/157.123.22.11", headers={'User-Agent' : "Magic Browser"})
html = urllib2.urlopen(req).read()
doc=lh.fromstring(html)
print ''.join(doc.xpath('.//*[@class="odd"]')[-1].text_content().split())
>>> 
Organization:ZenithDataSystems

【讨论】:

  • 嗨,当我运行它时,它显示 import lxml.html as lh ImportError: No module named lxml.html?
  • lxml.html 代表什么?
  • 谢谢,安装 lxml 后,还是有错误 Traceback (最近一次调用 last): File "ext.py", line 2, in ?将 lxml.html 导入为 lh 文件“/usr/lib64/python2.4/site-packages/lxml/html/__init__.py”,第 42 行,在? from lxml import etree ImportError: /usr/lib64/python2.4/site-packages/lxml/etree.so: undefined symbol: xmlMemDisplayLast
  • 是的,我使用的是 Python 2.4.3。使用 centos 5.5
  • 是的,我使用的是 Python 2.4.3。使用 centos 5.5
猜你喜欢
  • 2011-07-04
  • 2012-09-27
  • 2015-06-24
  • 2012-05-11
  • 2011-08-29
  • 2013-10-30
  • 1970-01-01
  • 1970-01-01
  • 2012-02-22
相关资源
最近更新 更多