美文网首页pythonIT实用分享
Python使用xpath爬虫查询身份证信息和手机号信息并写入E

Python使用xpath爬虫查询身份证信息和手机号信息并写入E

作者: sunshaoping | 来源:发表于2018-11-02 16:15 被阅读477次

    一.这个程序在网上还是有很多范例的,所以我就将大家的总结一下,然后形成自己的小程序,废话少说,上代码

    import time
    import requests
    from lxml import etree  # xpath模块
    import pandas as pd     # 写入Excel模块 
    
    # 获取身份信息
    def main():
        time1 = time.time()
        # 将要获取的身份证号
        df = pd.read_csv('C:/Users/admin/Desktop/shen.txt', sep='\t', header=None, dtype=str, na_filter=False)  # 打开存放身份证号的txt文件
        print(df)
        idcard1=[]  # 身份证列表
        gender1 = []    # 性别列表
        birthday1 = []  # 生日列表
        address1 = []   # 地址列表
    
        # 循环获取身份证信息
        for i in range(0,len(df)):
            try:
                if len(df.iloc[i,0]) == 18:
                    print(df.iloc[i,0]) # 获取每行的身份证号
                    idcard1.append(df.iloc[i,0]) # 记录身份证号
                    url="http://qq.ip138.com/idsearch/index.asp?action=idcard&userid="+df.iloc[i,0]+"&B1=%B2%E9+%D1%AF" # 发起请求
                    html=requests.get(url).content  # 接受返回值
                    selector=etree.HTML(html)   # 处理返回值
                    sex=selector.xpath('//td[@class="tdc2"][1]/text()') # 匹配指定元素
                    print(sex[0])   # 性别
                    print(sex[1])   # 生日
                    print(sex[-1])    # 地址
                    gender1.append(sex[0])
                    birthday1.append(sex[1])
                    address1.append(sex[-1])
                else:
                    idcard1.append(df.iloc[i, 0])
                    gender1.append("空")
                    birthday1.append("空")
                    address1.append("空")
            except Exception as e:
                print(e)
    
        # 计算爬虫时间
        time2 = time.time()
        print('爬虫结束!总共耗时:' + str(time2 - time1) + 's')
    
        # 写入表格
        time3 = time.time()
        data = pd.DataFrame({'id': idcard1,'grender': gender1,'birthday': birthday1,'address': address1})
        pd.DataFrame.to_excel(data, "D:\\1.xls", header=True, encoding='gbk', index=False)
        time4 = time.time()
        print("写入表格完成!总共耗时:" + str(time4 - time3) + "s")
    
    
    # 获取手机号信息
    def main2():
        time1 = time.time()
        # 将要获取的身份证号
        df = pd.read_csv('C:/Users/admin/Desktop/shouji.txt', sep='\t', header=None, dtype=str, na_filter=False)  # 打开存放身份证号的txt文件
        print(df)
        phone1=[]  # 手机号列表
        address1 = []   # 地址列表
    
        # 循环获取身份证信息
        for i in range(0,len(df)):
            try:
                if len(df.iloc[i,0]) == 15:
                    print(df.iloc[i,0][-11:]) # 获取每行的身份证号
                    phone1.append(df.iloc[i,0]) # 记录身份证号
                    url = "http://www.ip138.com:8080/search.asp?mobile="+df.iloc[i,0][-11:]+"&action=mobile"  # 发起请求
                    html=requests.get(url).content  # 接受返回值
                    selector=etree.HTML(html)   # 处理返回值
                    sex=selector.xpath('//tr[@class="tdc"][2]/td[@class="tdc2"]/text()') # 匹配指定元素
                    for i in sex:
                        print(i)
                        address1.append(i)
                else:
                    phone1.append(df.iloc[i, 0])
                    address1.append("空")
            except Exception as e:
                print(e)
    
        # 计算爬虫时间
        time2 = time.time()
        print('爬虫结束!总共耗时:' + str(time2 - time1) + 's')
    
        # 写入表格
        time3 = time.time()
        data = pd.DataFrame({'id': phone1,'address': address1})
        pd.DataFrame.to_excel(data, "D:\\1.xls", header=True, encoding='gbk', index=False)
        time4 = time.time()
        print("写入表格完成!总共耗时:" + str(time4 - time3) + "s")
    
    
    # 主函数入口
    if __name__ == '__main__':
        main()
    

    总结:
    1.在这次过程中,遇到的问题就是如何使用xpath匹配元素,由于太长时间没有使用xpath了,所以有点不太会用了,百度一下,需要下载一个插件
    2.在运行程序中,需要安装需要的模块,Xpath和Excel模块
    二.xpath安装步骤
    1.下载xpath插件
    xpath链接:https://pan.baidu.com/s/1dFgzBSd 密码:zwvb,感谢这位网友,我从这拿到了。
    2.在谷歌浏览器中“更多工具”找到这个“扩展程序”选项菜单,进入其中
    3.进入到扩展插件的界面,把下载好的离线xpath插件
    拖到这个扩展界面,他就会有提示,松开鼠标直接安装即可。安装成功之后重启一下谷歌浏览器即可
    4.使用快捷键ctrl+shift+x调出xpath。

    相关文章

      网友评论

        本文标题:Python使用xpath爬虫查询身份证信息和手机号信息并写入E

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