我尝试获取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)
问题是:
print re.findall("res/[0-9]+", html)
就是提供复制品。
我不能使用:
print re.findall("^res/[0-9]+$", html)
我读过python文档,但它们没有帮助。
发布于 2011-01-01 01:48:27
这是因为在源代码中有多个链接副本。
通过将它们放在一个集合中,您可以很容易地使它们具有唯一性。
>>> 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'])
但是,如果您要做比这更复杂的事情,我建议您使用可以解析HTML的库。BeautifulSoup或lxml。
https://stackoverflow.com/questions/4571468
复制相似问题