Python 爬虫入门三(网页)

获取网页里所有的链接

def getAllLink(url):
    html = urlopen(url)
    bs = BeautifulSoup(html, 'html.parser')
    for link in bs.find_all('a'):
        if 'href' in link.attrs:
            print (link.attrs['href'])

 

获取百度百科里所有相关的链接

def getAllBaikeLink(url):
    html = urlopen(url)
    bs = BeautifulSoup(html, 'html.parser')
    for link in bs.find('div', {'class': 'content'}).find_all('a', {'target': '_blank'}, href = re.compile('^/item/*')):
        if 'href' in link.attrs:
            print(link.attrs['href'])


------------------------------------------相同---------------------------------------------


def getAllBaikeLink(url):
    html = urlopen(url)
    bs = BeautifulSoup(html, 'html.parser')
    for link in bs.find('div', {'class': 'content'}).find_all('a', {'target': '_blank', 'href' : re.compile('^/item/*')}):
        if 'href' in link.attrs:
            print(link.attrs['href'])

遍历一个网站所有内链(去重)

pages = set()
def getAllLinks(后缀):
    global pages
    html = urlopen('网页地址'.format(后缀))
    bs = BeautifulSoup(html, 'html.parser')
    for link in bs.find_all('a', href=re.compile('正则')):
        if link.attrs['href'] not in pages:
            #得到一个新的页面
            newPage = link.attrs['href']
            print(newPage)
            pages.add(newPage)
            getAllLinks(newPage)

遍历一个网站所有内链并打印信息(去重) 】

pages = set()
def getAllLinksData(后缀):
    global pages
    html = urlopen('网页地址'.format(后缀))
    bs = BeautifulSoup(html, 'html.parser')
    try:
        print (bs.h1.get_text())
        print (bs.find(id='xxx').find('li').find('a').attrs['href'])
    except AttributeError:
        print ("页面属性缺少")

    for link in bs.find_all('a',href=re.compile('正则')):
        if link.attrs['href'] not in pages:
            #得到一个新的页面
            newPage = link.attrs['href']
            print(newPage)
            pages.add(newPage)
            getAllLinksData(newPage)

                                       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值