簡體   English   中英

如何從HTML字符串中提取IP地址?

[英]How to extract an IP address from an HTML string?

我想使用Python從字符串(實際上是單行HTML)中提取IP地址。

>>> s = "<html><head><title>Current IP Check</title></head><body>Current IP Address: 165.91.15.131</body></html>"

- '165.91.15.131'是我想要的!

我嘗試使用正則表達式,但到目前為止我只能使用第一個數字。

>>> import re
>>> ip = re.findall( r'([0-9]+)(?:\.[0-9]+){3}', s )
>>> ip
['165']

但我對reg-expression缺乏把握; 上面的代碼是從網上其他地方找到並修改的。

刪除您的捕獲組:

ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', s )

結果:

['165.91.15.131']

筆記:

  • 如果您正在解析HTML,那么查看BeautifulSoup可能是個好主意。
  • 正則表達式匹配一些無效的IP地址,例如0.00.999.9999 這不一定是個問題,但您應該了解它並可能處理這種情況。 您可以將+更改為{1,3}以進行部分修復,而不會使正則表達式過於復雜。

您可以使用以下正則表達式僅捕獲有效的IP地址

re.findall(r'\b25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\.25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\.25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\.25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\b',s)

回報

['165', '91', '15', '131']
import re

ipPattern = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')

findIP = re.findall(ipPattern,s)

findIP contains ['165.91.15.131']

從日志中找到IP地址的最簡單方法..

 s = "<html><head><title>Current IP Check</title></head><body>Current IP Address: 165.91.15.131</body></html>"
 info = re.findall(r'[\d.-]+', s)

在[42]中:info

出[42]:['165.91.15.131']

您可以使用以下正則表達式來提取有效的IP而不會出現以下錯誤
1.有些檢測到123.456.789.111為有效IP
2.有些不檢測127.0.00.1為有效IP
3.有些人不會像08.8.8.8那樣檢測以零開頭的IP

所以在這里我發布一個適用於所有上述條件的正則表達式。

注意:我已經提取了超過2百萬個IP而沒有任何跟隨正則表達式的問題。

(?:(?:1\d\d|2[0-5][0-5]|2[0-4]\d|0?[1-9]\d|0?0?\d)\.){3}(?:1\d\d|2[0-5][0-5]|2[0-4]\d|0?[1-9]\d|0?0?\d)

這就是我做到的。 我覺得它太干凈了

import re
import urllib2

def getIP():
    ip_checker_url = "http://checkip.dyndns.org/"
    address_regexp = re.compile ('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
    response = urllib2.urlopen(ip_checker_url).read()
    result = address_regexp.search(response)

    if result:
            return result.group()
    else:
            return None

get_IP()將ip返回到字符串或None

如果您更喜歡更准確的解析或更改Web服務提供者,則可以將address_regexp替換為其他正則表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM