在python中清除废弃的url

2024-09-27 07:25:43 发布

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

我正在写一个网页刮板从网站上刮链接。它工作正常,但输出链接不干净。它输出断开的html链接,也检索相同的html链接。这是密码

links = re.findall('<a class=.*?href="?\'?([^"\'>]*)', sourceCode)
            for link in links:  
                print link      

这就是输出的样子

/preferences?hl=en&someting
/preferences?hl=en&someting
/history/something
/history/something
/support?pr=something
/support?pr=something
http://www.web1.com/parameters
http://www.web1.com/parameters
http://www.web2.com/parameters
http://www.web2.com/parameters

我尝试用这个正则表达式清理非html的链接

link = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', link)
                    print link

它清除url,但在其中添加方括号。没有方括号怎么洗这个?我应该如何防止打印同一个网址两次或多次

/preferences?hl=en&someting -> []
http://www.web1.com/parameters -> [http://www.web1.com/parameters]

Tags: recomhttp链接htmlwwwlinklinks
2条回答

因为re.findall返回项目列表,所以在匹配的项目[]周围得到^{

link = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', link)
# pay attention on iteration over set(links) and not links
for link in set(links):
    print link

请注意,我已经将^{}创建添加到for loop中,以仅获取唯一链接,这样您就可以防止打印相同的url。你知道吗

尝试使用

links = re.findall('href="(http.*?)"', sourceCode)
links = sorted(set(links))

for link in links:
    print(links)

这将只获取以http开头的链接,并删除重复项并对其排序

相关问题 更多 >

    热门问题