re.findall问题(重复)

SnZ*_*SnZ 3 html python regex

我试图获取4chan网站的源代码,并获得线程的链接.

我有regexp的问题(不工作).资源:

import urllib2, re

req = urllib2.Request('http://boards.4chan.org/wg/')
resp = urllib2.urlopen(req)
html = resp.read()

print re.findall("res/[0-9]+", html)
#print re.findall("^res/[0-9]+$", html)
Run Code Online (Sandbox Code Playgroud)

问题是:

print re.findall("res/[0-9]+", html)
Run Code Online (Sandbox Code Playgroud)

给予重复.

我不能用:

print re.findall("^res/[0-9]+$", html)
Run Code Online (Sandbox Code Playgroud)

我已经阅读过python docs,但是他们没有帮助.

Len*_*bro 11

那是因为源中有多个链接副本.

您可以通过将它们放入一组来轻松地使它们独一无二.

>>> print set(re.findall("res/[0-9]+", html))
set(['res/3833795', 'res/3837945', 'res/3835377', 'res/3837941', 'res/3837942',
'res/3837950', 'res/3100203', 'res/3836997', 'res/3837643', 'res/3835174'])
Run Code Online (Sandbox Code Playgroud)

但是如果你要做比这更复杂的事情,我建议你使用一个可以解析HTML的库.无论是BeautifulSoupLXML.