如何用Python从HTML中获取href链接?

60 投票
10 回答
241167 浏览
提问于 2025-04-16 00:10
import urllib2

website = "WEBSITE"
openwebsite = urllib2.urlopen(website)
html = getwebsite.read()

print html

到目前为止,一切都很好。

但是我只想从纯文本的HTML中提取出链接(href链接)。我该怎么解决这个问题呢?

10 个回答

15

可以考虑使用一个叫做Beautiful Soup的HTML解析库。

http://www.crummy.com/software/BeautifulSoup/

你可以这样做:

import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(html)
for link in soup.findAll("a"):
    print link.get("href")
36

你可以使用HTMLParser模块。

代码可能看起来像这样:

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):

    def handle_starttag(self, tag, attrs):
        # Only parse the 'anchor' tag.
        if tag == "a":
           # Check the list of defined attributes.
           for name, value in attrs:
               # If href is defined, print it.
               if name == "href":
                   print name, "=", value


parser = MyHTMLParser()
parser.feed(your_html_string)

注意:在Python 3.0中,HTMLParser模块被重命名为html.parser。使用2to3工具时,它会自动调整导入的内容,以便将你的代码转换为3.0版本。

131

试试用 Beautifulsoup

from BeautifulSoup import BeautifulSoup
import urllib2
import re

html_page = urllib2.urlopen("http://www.yourwebsite.com")
soup = BeautifulSoup(html_page)
for link in soup.findAll('a'):
    print link.get('href')

如果你只想要以 http:// 开头的链接,可以使用:

soup.findAll('a', attrs={'href': re.compile("^http://")})

在 Python 3 和 BS4 中应该是:

from bs4 import BeautifulSoup
import urllib.request

html_page = urllib.request.urlopen("http://www.yourwebsite.com")
soup = BeautifulSoup(html_page, "html.parser")
for link in soup.findAll('a'):
    print(link.get('href'))

撰写回答