【问题标题】:parsing proxy adress with Regex and python使用 Regex 和 python 解析代理地址
【发布时间】:2020-10-11 07:28:21
【问题描述】:

我试图通过解析一个字符串来检索代理的地址,该字符串包含隐藏在大量无用文本中的 ip 和端口。 经过多次不成功的尝试后,我开始研究正则表达式。

def parseLine(line):
stock = []
listpat = ["\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", "^(6553[0-5]|655[0-2]\d|65[0-4]\d\d|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)$ "] #ip, port

for elem in line:
    for pat in listpat:
        result = re.match(pat, elem)
        if result:
            stock.append(result)

with open('list.csv', 'a') as f:
    writer = csv.writer(f)
    for cell in stock:
        writer.writerows(cell)

这两个正则表达式分别是 IP 和端口的模式。 这是我正在研究的字符串的示例:

<tr class="odd"><td><input id="row1" name="c1" onclick="choice()" type="checkbox" value="2057281.204.168.1069921863141"/></td><td>201.204.168.106<script type="text/javascript">document.write(":"+t+w+q+p+q)</script></td><td>high-anonymous</td><td><dfn title="01:09:16 AM GMT">Jun-19-2020</dfn></td><td>Costa Rica</td><td class="organization">San Antonio De Belen</td></tr>

我感兴趣的唯一信息是

201.204.168.106

&lt;script type="text/javascript"&gt;document.write(":"+t+w+q+p+q)&lt;/script&gt;的结果

我的错误是什么?

【问题讨论】:

  • 使用re.search()而不是re.match(),后者将表达式绑定到字符串的开头(在您的示例中为&lt;tr...&gt;)。

标签: python regex beautifulsoup proxy


【解决方案1】:

您正在寻找re.search() / re.findall() 而不是re.match()。后者将表达式绑定到无法找到任何地址的字符串的开头。请参阅以下工作代码:

import re

string = """
<tr class="odd"><td><input id="row1" name="c1" onclick="choice()" type="checkbox" value="2057281.204.168.1069921863141"/></td><td>201.204.168.106<script type="text/javascript">document.write(":"+t+w+q+p+q)</script></td><td>high-anonymous</td><td><dfn title="01:09:16 AM GMT">Jun-19-2020</dfn></td><td>Costa Rica</td><td class="organization">San Antonio De Belen</td></tr>
"""

rx = re.compile(r'(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)')

for possible_ip in rx.findall(string):
    print(possible_ip)

产量

201.204.168.106

【讨论】:

  • 这很奇怪,这个解决方案对我不起作用......我必须检查几件事才能确定。
  • 我的问题是我的字符串未被识别为这样。添加的 str() 函数允许更正
猜你喜欢
  • 1970-01-01
  • 2013-06-28
  • 2013-04-14
  • 2020-11-14
  • 2019-05-01
  • 2012-10-24
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多