美文网首页
爬取解析中华人民共和国县以上行政区划代码

爬取解析中华人民共和国县以上行政区划代码

作者: 杨闯 | 来源:发表于2020-03-16 22:42 被阅读0次

    以前都听别人说爬虫功能,我也没有什么强烈的需求爬取什么数据,曾经有想过一些省市县的分布应该是有一个长期的维持,那么这些数据来自于哪里呢,是可以通过民政部官网获取,那么获取了,是否能够进行解析找到对应的数据呢,经过试验,真正抓取到了数据并且把数据分解出来了,可以留备后用。

    from urllib.request import urlopen  #查找 Python 的 request 模块(在 urllib 库里面),只导入一个 urlopen 函数,urllib 是 Python 的标准库,就是说不用额外安装就可以运行
    from bs4 import BeautifulSoup
    import re # 进行正则表达式验证
    
    html = urlopen("http://www.mca.gov.cn/article/sj/xzqh/2020/2020/202003061536.html")
    bsObj = BeautifulSoup(html.read(),"html.parser")
    nameList = bsObj.findAll("tr",{"height":"19"})
    for i,name in enumerate(nameList):
        if re.match(r'\n\n.*?\n\xa0\xa0 .*?\n\n\n\n\n\n\n',name.text):
            e = name.text.replace('\n', '')
            key = e.split('\xa0\xa0 ',1)[0]
            value =  e.split('\xa0\xa0 ',1)[1]
            print("111 key = "+key+" value = "+value)
        elif re.match(r'\n\n.*?\n\xa0.*?\n\n\n\n\n\n\n',name.text):
            e = name.text.replace('\n', '')  
            key = e.split('\xa0',1)[0]
            value =  e.split('\xa0',1)[1]
            print("222 key = "+key+" value = "+value)      
        elif re.match(r'\n\n.*?\n.*?\n\n\n\n\n\n\n',name.text):
            e = name.text.replace('\n\n', '')        
            key = name.text.split('\n',4)[2]
            value =  name.text.split('\n',4)[3]
            print("333 key = "+key+" value = "+value)      
    
    
    image.png

    通过以上内容,了解了一些知识,比如通过urlopen进行联网获取,通过BeautifulSoup进行html解析获取所需要的内容,通过re进行正则表达式的验证区分相关的字段内容,后边对一些内容进行详细的描述。

    相关文章

      网友评论

          本文标题:爬取解析中华人民共和国县以上行政区划代码

          本文链接:https://www.haomeiwen.com/subject/eohaehtx.html