python 练习0009

问题

一个HTML文件,找出里面的链接。

代码

import requests, re
from bs4 import BeautifulSoup

def get_html_text(url):
    try:
        r = requests.get(url)
        r.encoding = 'utf-8'
        return r.text
    except:
        return ''

def get_urls(html, base_url):
    soup = BeautifulSoup(html, 'html.parser')
    urls = set()
    for url in soup.find_all('a'):
        # 可能 <a> 标签中无 href 属性
        try:
            url = url['href']
            # 绝对路径 http://www.baidu.com/path/index.php?q=1
            absolute_url = r'((http|https|ftp)://)?(\w+)(\.\w+)+'
            # 相对路经 ./index.php
            relative_url = r'\.?(/\w+)+/?'

            absolute_url_pattern = re.compile(absolute_url, re.IGNORECASE))
            relative_url_pattern = re.compile(relative_url)

            if absolute_url_pattern.match(url):
                urls.add(url)
                continue
            if relative_url_pattern.match(url):
                url = base_url + url
                urls.add(url)
                continue                
        except:
            continue
    return urls
        

def show(urls):
    for url in urls:
        print(url)

if __name__ == '__main__':
    url = 'http://zzzsdust.com'
    html = get_html_text(url)
    urls = get_urls(html, url)
    show(urls)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值