我正在用 python 构建一个应用程序,我需要获取一个网页中所有链接的 URL。我已经有一个函数,它使用 urllib 从网络上下载 html 文件,并使用 readlines() 将其转换为字符串列表。
目前我有这段代码使用正则表达式(我不是很擅长)在每一行中搜索链接:
for line in lines:
result = re.match ('/href="(.*)"/iU', line)
print result
这不起作用,因为它只为文件中的每一行打印“无”,但我确定我正在打开的文件中至少有 3 个链接。
有人可以给我一些提示吗?
提前致谢
最佳答案
Beautiful Soup 几乎可以做到这一点:
from BeautifulSoup import BeautifulSoup as soup
html = soup('<body><a href="123">qwe</a><a href="456">asd</a></body>')
print [tag.attrMap['href'] for tag in html.findAll('a', {'href': True})]
关于python - 使用Python获取html文件上所有<a>标签中href属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/671323/