如何从html到Python获取一行文本

时间:2011-05-03 10:50:12

标签: python html

我正在创建一个程序,打印出用户的IP地址。 所以我想要做的是获取ipchicken.com的Html并打印出“名称地址”部分。 这是我目前的代码:

import urllib              
sock = urllib.urlopen("http://ipchicken.com")
htmlSource = sock.read()           
sock.close()
print htmlSource

现在我如何打印html的ip部分?

如果还有其他方法可以使用python获取用户的ip,请包括那个:)

4 个答案:

答案 0 :(得分:2)

使用HTML抓取库,例如BeautifulSoup

答案 1 :(得分:2)

我建议您使用比ifconfig.me更具编程性的内容而不是广告负载的ipchicken。 ifconfig.me在被cURL等查询时表现不同。

如果您要解析HTML并使用ipchicken输出IP地址,请使用BeautifulSoupElementTree

更新http://ip.appspot.com/程序化界面的东西。

答案 2 :(得分:2)

运行正则表达式以查找htmlSource

上的IP结构模式
ips = re.findall('(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})',
                 htmlSource)

变量ips将包含具有IP结构的所有文字。

整个代码看起来像:

import urllib,re           
sock = urllib.urlopen("http://ipchicken.com")
htmlSource = sock.read()           
sock.close()
print htmlSource
ips = re.findall('(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})', htmlSource)
print "IPs in page", ips

答案 3 :(得分:1)

您可以使用regular expression抓取其他文字中的文字。如果您提供htmlSource的相关部分,我们可以发布一个。

以下是有关检索IP地址的一些帖子:How to find out your IP address in Python