=\s]+)-6ren">
gpt4 book ai didi

python - 从html页面获取相关链接

转载 作者:太空宇宙 更新时间:2023-11-04 10:34:12 26 4
gpt4 key购买 nike

我只想从 html 页面中提取相对 url;有人建议这样做:

find_re = re.compile(r'\bhref\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'<>=\s]+)', re.IGNORECASE)

但它返回:

1/页面中的所有绝对和相对 URL。

2/url 可以用""'' 随机引用。

最佳答案

使用the tool for the job : HTML 解析器,例如 BeautifulSoup .

您可以 pass a function作为 find_all() 的属性值并检查href是否以http开头:

from bs4 import BeautifulSoup

data = """
<div>
<a href="http://google.com">test1</a>
<a href="test2">test2</a>
<a href="http://amazon.com">test3</a>
<a href="here/we/go">test4</a>
</div>
"""
soup = BeautifulSoup(data)
print soup.find_all('a', href=lambda x: not x.startswith('http'))

或者,使用 urlparsechecking for network location part :

def is_relative(url):
return not bool(urlparse.urlparse(url).netloc)

print soup.find_all('a', href=is_relative)

两种解决方案都打印:

[<a href="test2">test2</a>, 
<a href="here/we/go">test4</a>]

关于python - 从html页面获取相关链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24472957/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com