Python网页爬虫案例(仅供学习)

需求:需要在企查查上,自动批量获取企业的注册资本与成立日期。

解决方案

  1. 导入需要的库。

    # 文件操作库
    import re 
    import xlrd # excel文件读取
    import xlutils.copy # 文件复制
    
    # 其他功能库
    import time # 提供延时功能,给浏览器时间加载数据
    from urllib.parse import quote # 将单个字符串编码转化为 %xx 的形式
    
    # 浏览器操作库
    from selenium import webdriver 
    from selenium.webdriver.common.by import By
    
  2. 从excel表中获取需要获取的企业名称。

    # 从excel获取查询单位
    worksheet = xlrd.open_workbook(r'F:\Python\demo\测试.xls') # 参数是文件路径
    sheet1 = worksheet.sheet_by_name("Sheet1")# excel有多个sheet,检索该名字的sheet表格
    rows = sheet1.nrows # 获取行数
    inc_list = []  # 总数据
    for i in range(1,rows) :
        data = sheet1.cell_value(i, 0) # 取第1列数据
        inc_list.append(data)
    inc_len = len(inc_list) # 获取数据总数据长度
    
    # 为了不影响原来的文件,复制出一个新excel
    rd = xlrd.open_workbook("测试.xls", formatting_info = True) # 打开文件
    wt = xlutils.copy.copy(rd)   # 复制
    sheets = wt.get_sheet(0)   # 读取第一个工作表
    
  3. 伪装浏览器,模拟手动操作。

    # 伪装成浏览器,防止被识破
    option = webdriver.ChromeOptions()
    option.add_argument('--user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0"')
    driver = webdriver.Chrome(options=option)
    
    #模拟手动登录,打开登录页面
    driver.get('https://www.qichacha.com/user_login')
    time.sleep(8) # 等待8s,完成手动登录操作
    
  4. 进行批量查询。

    nonecs=0 # 没有查询到的次数
    cyname='' # 曾用名
    
    # 循环获取企业成立日期与注册资本
    for i in range(inc_len):
        print(inc_list[i]) # 输出企业名称
        url='https://www.qcc.com/web/search?key='+quote(inc_list[i]) # 转换企业名称,并拼接出url
        driver.get(url)
        time.sleep(3)  # 等待3s,让浏览器加载数据。因网络来定等待时间。
        zczb=''
        clrq=''
        try:
            # 爬取数据代码,此处略。
            # 第5步展视该部分代码。
            nonecs = 0 # 获取成功,重置次数为0
            zczb = re.findall("\d+\.?\d*", zczb.text)
            clrq = clrq.text
        except:
            nonecs = nonecs + 1 # 获取失败,次数+1
            zczb = 'none'
            clrq = 'none'
        # 打印获取内容
        print(zczb)
        print(clrq)
        print('--------------------------------------------')
        # 写入保存获取内容
        # 第6步展视该部分代码。
        if nonecs >= 3:
            driver.close()
            print('none次数以大于3次,可能遭网页限制,请检查。')
            print('以停止爬取--------------------------。')
            break
    driver.close()
    
  5. 爬取数据,每个异常处理都是一个获取方法,因为企业改名称或者其他原因,会使需要的数据位置发生改变,所以为了应对情况,多试着获取几个位置。

    # 位置一
    try:
    	# 获取企业注册资本
    	zczb = driver.find_element(by=By.CSS_SELECTOR,
    		value='body > div.default-layout > div.app-search.layout-content > div.container.m-t > div.adsearch-list.search-sticky-container > div > div.msearch > div > table > tr.frtrt.tsd0 > td:nth-child(3) > div.maininfo > div.relate-info > div:nth-child(1) > span:nth-child(2) > span')
    	# 获取企业成立日期
    	clrq = driver.find_element(by=By.CSS_SELECTOR,
    		value='body > div.default-layout > div.app-search.layout-content > div.container.m-t > div.adsearch-list.search-sticky-container > div > div.msearch > div > table > tr.frtrt.tsd0 > td:nth-child(3) > div.maininfo > div.relate-info > div:nth-child(1) > span:nth-child(3) > span')
    except:
    	print('---企业名称与搜索结果不一致,获取失败!')
    
    # 位置二
    try:
    	# 获取查询企业曾用名
    	cyname=driver.find_element(by=By.CSS_SELECTOR,
    		value='body > div.default-layout > div.app-search.layout-content > div.container.m-t > div.adsearch-list.search-sticky-container > div > div.msearch > div > table > tr:nth-child(1) > td:nth-child(3) > div > div.relate-info > div:nth-child(4) > span > span > span > em').text
    	if inc_list[i] == cyname and zczb == '':
    		zczb = driver.find_element(by=By.CSS_SELECTOR,
    			value='body > div.default-layout > div.app-search.layout-content > div.container.m-t > div.adsearch-list.search-sticky-container > div > div.msearch > div > table > tr:nth-child(1) > td:nth-child(3) > div > div.relate-info > div:nth-child(1) > span:nth-child(2) > span')
    		clrq = driver.find_element(by=By.CSS_SELECTOR,
    			value='body > div.default-layout > div.app-search.layout-content > div.container.m-t > div.adsearch-list.search-sticky-container > div > div.msearch > div > table > tr:nth-child(1) > td:nth-child(3) > div > div.relate-info > div:nth-child(1) > span:nth-child(3) > span')
    except:
    	print('---曾用名方法获取失败!')
    
  6. 保存数据。

    sheets.write(i+1, 2,zczb)  # 向 i 行 4 列的单元格写入内容
    sheets.write(i+1, 3,clrq)  # 向 i 行 5 列的单元格写入内容
    wt.save("测试2.xls")  # 保存
    
  7. 关闭对象

    driver.close()
    
posted @ 2024-06-04 16:38  克峰同学  阅读(3)  评论(0编辑  收藏  举报