2012-10-11 80 views
0

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

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

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

我怎么能直接将网站的内容没有任何新的安装一样得到http://www.ip-adress.com/ip_tracer/157.123.22.11

+0

@jesseslu你需要下载文件吗?或者只解析和访问它? –

+0

不需要下载文件 – AntiGMO

+1

那么,你需要得到的HTML文件:) – root

回答

0

您将通过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 
+0

嗨,当我运行它,它显示导入lxml.html为lh ImportError:没有模块名为lxml.html? – AntiGMO

+0

lxml.html代表什么? – AntiGMO

+0

谢谢,安装lxml后,它仍然有错误回溯(最近最后一次调用最后): 文件“ext.py”,第2行,在? import lxml.html as 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 – AntiGMO

3

我喜欢BeautifulSoup,它可以很容易地访问HTML字符串中的数据。 实际的复杂程度取决于HTML是如何形成的。如果HTML使用'id'和'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 
+0

我如何直接获取网站内容,而不需要像http://www.ip-adress.com/ip_tracer/157.123.22.11 – AntiGMO

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() 
+0

这样的新安装如何直接获取网站内容没有像http://www.ip-adress.com/ip_tracer/157.123.22.11这样的新安装 – AntiGMO

+0

请参阅我的编辑了解如何阅读内容。 – 2012-10-11 07:05:00

+0

请勿使用'urllib2'!改用'requests'。 – egasimus