nova-week4

任务

继续优化上周的两个爬取链接和内链的程序,对爬取内容进行筛选

注:在过程中遇到问题:“ImportError: cannot import name etree”

解决办法:

  1. 网上提到可能是把文件夹命名为了"lxml"—btw无果
  2. 问题不在1,把setting-project里的第三方库"lxml"升级为最新版,就OK了???(黑人问号,原理不知,可能是版本冲突)

mission 1:

import requests
import json
from lxml import etree
import re
def get_html(url):
    #获取网站的html代码并将其用lxml初始化,并返回
    Html=requests.get(url)
    html=etree.HTML(Html.text)
    return html
def get_link(html):
    #获取html中的链接地址,并写入文件
    with open(r"C:\Users\lenovo\Desktop\untitled\nova\week4\link.json",'w')as f:
        link=html.xpath("//a/@href")
        link_selected=[]
        for i in link:
            if re.match("/.+\.htm",i):
                link_selected.append(i)
        Json=json.dumps(link_selected,sort_keys=True, indent=4, separators=(',', ': '))
        f.write(Json)
if __name__=="__main__":
    html=get_html(r'http://www.nju.edu.cn/')
    get_link(html)

结果:对爬取内容进行了筛选,共爬取64条链接

mission 2:

import re
import requests
from lxml import etree
import json
def json_read():
    #读取json文件中的内容
    with open(r"C:\Users\lenovo\Desktop\untitled\nova\week4\link.json",'r') as f:
        link=json.loads(f.read())
    return link
def get_postfix(url):
    #爬取对应url下的链接地址
    Html=requests.get(url)
    html=etree.HTML(Html.text)
    link=html.xpath("//a/@href")
    return link
def url_search(link_pull,link):
    #寻找匹配的内链地址并输出;通过递归穷尽所有分支
    for i in link:
        if re.match(r"/.+\.htm",i):
            #因为爬取后最后一条链接是图片,没想到什么好办法,通过这个判断去掉这一条
            if ".jpg" in i:
                break
            if str("http://www.nju.edu.cn"+i) in link_pull:
                continue
            else:
                print("http://www.nju.edu.cn"+i)
                link_pull.append(str("http://www.nju.edu.cn"+i))
                post=get_postfix("http://www.nju.edu.cn"+i)
                if post!=[]:
                    url_search(link_pull,post)
    return
if __name__=="__main__":
    link=json_read()
    link_pull=link
    url_search(link_pull,link)

知识点:爬取下的链接是绝对地址!!!前面只需要加"http://www.nju.edu.cn"

每个链接之间是相互独立的,而不是父子节点之间的关系!!!

结果:共爬取下来423条内链

猜你喜欢

转载自blog.csdn.net/sunflower_zzn/article/details/88850510