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

use*_*012 41 html python beautifulsoup href hyperlink

import urllib2

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

print html
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.

但我只希望纯文本HTML中的href链接.我怎么解决这个问题?

sys*_*out 91

尝试使用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')
Run Code Online (Sandbox Code Playgroud)

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

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

  • 提醒人们最近遇到这个答案,Python 3不再支持BeautifulSoup3,最新版本是BeautifulSoup4,您可以使用“from bs4 import BeautifulSoup”导入它 (6认同)

Ste*_*hen 29

您可以使用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)
Run Code Online (Sandbox Code Playgroud)

注意:HTMLParser模块已在Python 3.0中重命名为html.parser.将源转换为3.0时,2to3工具将自动调整导入.


Pet*_*ons 12

看看使用漂亮的汤html解析库.

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

你会做这样的事情:

import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(html)
for link in soup.findAll("a"):
    print link.get("href")
Run Code Online (Sandbox Code Playgroud)


Raa*_*mEE 8

使用BS4执行此特定任务似乎有点过分.

尝试改为:

website = urllib2.urlopen('http://10.123.123.5/foo_images/Repo/')
html = website.read()
files = re.findall('href="(.*tgz|.*tar.gz)"', html)
print sorted(x for x in (files))
Run Code Online (Sandbox Code Playgroud)

我在http://www.pythonforbeginners.com/code/regular-expression-re-findall上找到了这段漂亮的代码,对我很有用.

我仅在我从一个公开文件夹中提取文件列表的场景中测试了它,该文件夹中公开了files \文件夹,例如:

在此输入图像描述

我得到了URL下的files\folders的排序列表


sak*_*sak 6

回答这个问题已经太晚了,但它适用于最新的 python 用户:

from bs4 import BeautifulSoup
import requests 


html_page = requests.get('http://www.example.com').text

soup = BeautifulSoup(html_page, "lxml")
for link in soup.findAll('a'):
    print(link.get('href'))
Run Code Online (Sandbox Code Playgroud)

不要忘记安装“ requests ”和“ BeautifulSoup ”包以及“ lxml ”。将 .text 与 get 一起使用,否则会引发异常。

lxml ”用于删除要使用哪个解析器的警告。您还可以使用适合您情况的“ html.parser ”。


0xh*_*hes 5

与真正的大师相比,我的答案可能很糟糕,但是使用一些简单的数学,字符串切片,查找和urllib,这个小脚本将创建一个包含链接元素的列表.我测试谷歌和我的输出似乎是对的.希望能帮助到你!

import urllib
test = urllib.urlopen("http://www.google.com").read()
sane = 0
needlestack = []
while sane == 0:
  curpos = test.find("href")
  if curpos >= 0:
    testlen = len(test)
    test = test[curpos:testlen]
    curpos = test.find('"')
    testlen = len(test)
    test = test[curpos+1:testlen]
    curpos = test.find('"')
    needle = test[0:curpos]
    if needle.startswith("http" or "www"):
        needlestack.append(needle)
  else:
    sane = 1
for item in needlestack:
  print item
Run Code Online (Sandbox Code Playgroud)


reu*_*ano 5

这是@stephen 答案的懒惰版本

import html.parser
import itertools
import urllib.request

class LinkParser(html.parser.HTMLParser):
    def reset(self):
        super().reset()
        self.links = iter([])

    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            for (name, value) in attrs:
                if name == 'href':
                    self.links = itertools.chain(self.links, [value])


def gen_links(stream, parser):
    encoding = stream.headers.get_content_charset() or 'UTF-8'
    for line in stream:
        parser.feed(line.decode(encoding))
        yield from parser.links
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

>>> parser = LinkParser()
>>> stream = urllib.request.urlopen('http://stackoverflow.com/questions/3075550')
>>> links = gen_links(stream, parser)
>>> next(links)
'//stackoverflow.com'
Run Code Online (Sandbox Code Playgroud)


Spa*_*pas 5

在 BeautifulSoup 和 Python 3 中使用请求:

import requests 
from bs4 import BeautifulSoup


page = requests.get('http://www.website.com')
bs = BeautifulSoup(page.content, features='lxml')
for link in bs.findAll('a'):
    print(link.get('href'))
Run Code Online (Sandbox Code Playgroud)