使用Python获取html文件中所有<a>标签中的href属性值

rog*_*pvl 1 html python regex parsing

我正在python中构建一个应用程序,我需要在一个网页中获取所有链接的URL.我已经有一个函数使用urllib从web下载html文件,并将其转换为带有readlines()的字符串列表.

目前我有这个代码使用正则表达式(我不是很擅长)来搜索每一行中的链接:

for line in lines:
    result = re.match ('/href="(.*)"/iU', line)
    print result
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为它只为文件中的每一行打印"无",但我确信至少在我打开的文件上有3个链接.

有人可以给我一个暗示吗?

提前致谢

Ign*_*ams 11

美丽的汤几乎可以做到这一点:

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})]
Run Code Online (Sandbox Code Playgroud)


小智 8

BeautifulSoup的另一个替代品是lxml(http://lxml.de/);

import lxml.html
links = lxml.html.parse("http://stackoverflow.com/").xpath("//a/@href")
for link in links:
    print link
Run Code Online (Sandbox Code Playgroud)