用不同方式采集网页链接

要求:通过程序下载www.pku.edu.cn网页,采用不同方法将链接全部采集出【注:仅要带有href,且href的值不能以#开始,不能含有JavaScript/vbscript。】。
   1、用字符串处理办法,将所有链接采集出,格式是名称及其对应链接,注:不能依赖BS4;
   2、用正则表达式的方法,将所有链接采集出,格式是名称及其对应链接,注:不能依赖BS4;
   3、用BS的方法,将所有链接采集出,格式是名称及其对应链接;

链接:点击打开链接

代码1:

import requests
###  获取网页内容
url = 'http://www.pku.edu.cn'#定义url
res = requests.get(url)
res.encoding = "utf-8"  # 设置网页编码
###将网页内容整合为一行
strTxt=res.text.replace('\n','')

###       开始处理字符串    ##############
#分割字符串
allFind=strTxt.split(r"</a>")
#用字典来保存链接
dictA={}
#对每一个含有链接的str做处理
for include_a in allFind:
    #寻找链接的开始位置
    if('<a' in include_a ):
        #找到<a,并把之前的(没用的)都截断
        index_a=include_a.index('<a ')
        tem=include_a[index_a:]
        #找到’>‘,这样>后面的就是链接名称
        if ('href' in tem and '>' in tem ):
            #print(tem)
            #这样一分割,nameList[1]就是名称
            nameList = tem.split('>')
            name=nameList[1]
            #print(name[1])
            ##再次分割,href的后“之前的就是需要的东西
            index_href=nameList[0].index('href')
            ##+6直接去掉    href="
            hrefList=nameList[0][index_href+6:].split("\"")
            #href就是  hrefList[0]
            href=hrefList[0]
            #print(href[0])
            #做一些判断 按照要求,href开头不能为#,href中不能含有javascript/vbscript,有一些图片,直接删除
            if (href != '') and (href[0]!= '#') and ('javascript' not in href) and (
                'vbscript' not in href) and 'img'not in name and name!="":
                #做一些优化,如果连接不完整,则补上前缀
                if href[0:4]!='http':
                    href='http://www.pku.edu.cn/'+href
                dictA[name]=href
            #print('------------------------------')
#######                输出保存           ##########################################################
numA=0
for i in dictA:
    print(i,dictA[i],sep="    ")
    numA+=1
print(numA)

fd=open('./txt/1.txt','w',encoding='utf-8')
for i in dictA:
    print(i,dictA[i],file=fd,sep="\t")
fd.close()

代码2:

import requests
import re
####  获取网页内容    ############################
url = 'http://www.pku.edu.cn'#定义url
res = requests.get(url)
res.encoding = "utf-8"  # 设置网页编码
###将网页内容整合为一行
strTxt=res.text.replace('\n','')

###       开始处理字符串    ########################
#找到所有的链接
allFind=re.findall(r"<a .*?</a>",strTxt)
#用来保存最后的链接
dictA={}
#对每个含有链接的字符串进行处理
for include_a in allFind:
    ##分割字符串,则split_a[2]为名称,split_a[1]为含有href的字符串
    split_a=re.split('>|<',include_a)
    #print(con[2], con[1], sep="   $$$$$  ")
    #保存名称
    name=split_a[2]
    #只处理名字不为空且含有href的字符串
    if len(name)>0 and 'href' in split_a[1]:
        #print(con[1])
        #正则表达式,将href匹配出来
        match_include_href=re.search(r'href=".*?"',split_a[1])
        #处理一些奇怪的异常,
        if match_include_href is None:
            continue
        #截取""的东西
        match_include_yinhao = re.search(r'".*?"', match_include_href.group())
        #去掉左右两边的引号
        strHref=match_include_yinhao.group().strip('"')
        # 做一些判断 按照要求,href开头不能为#,href中不能含有javascript/vbscript,有一些图片,直接删除
        if (strHref !='') and (strHref[0]!='#')and ('javascript' not in strHref )and ('vbscript'  not in strHref):
            # 做一些优化,如果连接不完整,则补上前缀
            if strHref[0:4] != 'http':
                strHref = 'http://www.pku.edu.cn/' + strHref
            dictA[name] = strHref
            #print('------------------------------------')
#######                输出保存           ##########################################################
numA=0

for i in dictA:
    print(i,dictA[i],sep="    ")
    numA+=1

print(numA)

fd=open('./txt/2.txt','w',encoding='utf-8')
for i in dictA:
    print(i,dictA[i],file=fd,sep="\t")
fd.close()

代码3:

import requests
from bs4 import BeautifulSoup
####  获取网页内容
url = 'http://www.pku.edu.cn'#定义url
res = requests.get(url)
res.encoding = "utf-8"  # 设置网页编码

####       开始处理网页内容   ########################
soup = BeautifulSoup(res.text, "html.parser")

#print(soup)
#查找带有href的链接
a_include_href=soup.select('a[href]')
#用来保存链接
dictA={}
#对每一个链接进行处理
for include_a in a_include_href:
    #name 就是include_a.get_text(),href=include_a.attrs['href']
    name=include_a.get_text()
    href=str(include_a.attrs['href'])
    # 做一些判断 按照要求,href开头不能为#,href中不能含有javascript/vbscript,有一些图片,直接删除
    if  (href !='') and (href[0]!='#')and ('javascript' not in href )and ('vbscript'  not in href )and (name!="")and( 'img' not in name ):
        # 做一些优化,如果连接不完整,则补上前缀
        if href[0:4] != 'http':
            tem = 'http://www.pku.edu.cn/' + href
            dictA[name] = tem
        else:
            dictA[name]=href
#######                输出保存           ##########################################################
num_A=0
for i in dictA:
    if(i.strip(' ')!='' ):
        print(i, dictA[i],sep="   ")
        num_A+=1
print("num_ral   :",num_A)
#print(dictA[''])

fd=open('./txt/3.txt','w',encoding='utf-8')
for i in dictA:
    print(i,dictA[i],file=fd,sep="\t")
fd.close()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章