这个正则表达式有什么错

2024-09-27 21:34:02 发布

您现在位置:Python中文网/ 问答频道 /正文

links = re.findall('href="(http(s?)://[^"]+)"',page)

我有一个正则表达式来查找网站中的所有链接,我得到以下结果:

('http://asecuritysite.com', '')
('https://www.sans.org/webcasts/archive/2013', 's')

当我想要的只是这个:

http://asecuritysite.com
https://www.sans.org/webcasts/archive/2013

如果我去掉href后面的"(,它会给我很多错误,有人能解释为什么吗?你知道吗


Tags: httpsorgrecomhttp网站wwwpage
3条回答

如果使用多个捕获组,re.findall返回元组列表而不是字符串列表。尝试以下操作(仅使用单个组):

>>> import re
>>> page = '''
...     <a href="http://asecuritysite.com">here</a>
...     <a href="https://www.sans.org/webcasts/archive/2013">there</a>
...     '''
>>> re.findall(r'href="(https?:\/\/[^"]+)"',page)
['http://asecuritysite.com', 'https://www.sans.org/webcasts/archive/2013']

根据^{} documentation

If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.

尝试摆脱第二组(原始模式中的(s?)):

links = re.findall('href="(https?:\/\/[^"]+)"',page)

你做错的是试图用Regex解析HTML。先生,这是罪过。你知道吗

See here for the horrors of Regex parsing HTML

另一种方法是使用lxml这样的东西来解析页面并提取链接

urls = html.xpath('//a/@href')

相关问题 更多 >

    热门问题