爱企查与天眼查也来啦~

续企查查之后,爱企查作为不用登录也能查的网站,还自带json返回,方便了数据的获取,深受我的喜爱。

天眼查只能手机号登录,没有企查查QQ登录的方便,勉强把它拉过来吧,他既没有json返回,网页上也没有任何字典数据,只能从表格中获取。第一次使用天眼查爬取的时候发现了反爬字体 tyc-num ,查阅了各种资料才知道需要用 TTFont来输出其数字对应关系(不错,以后自己也能用用),所需 tyc-num.woff 的资源可以在天眼查网站上找到下载,也可以去资源中找到,多的就不说了,直接上代码:

# _*_ coding:utf-8 _*_
# FileName: get_company.py
# IDE: PyCharm
# 菜菜代码,永无BUG!

import json
import requests
from urllib import parse
from bs4 import BeautifulSoup
from fontTools.ttLib import TTFont
from get_cookies import get_cookies_from_chrome

# https://aiqicha.baidu.com/
# https://www.tianyancha.com/

"""
from faker import Faker
fake = Faker()
headers = {'User-Agent': fake.user_agent()}
"""

headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"}

aqc_search_url = "https://aiqicha.baidu.com/s?t=0&"
aqc_detail_url = "https://aiqicha.baidu.com/company_detail_"
aqc_data_url = "https://aiqicha.baidu.com/detail/basicAllDataAjax?pid="
tyc_search_url = "https://www.tianyancha.com/search?"

tyc_cookie = get_cookies_from_chrome('tianyancha.com')

# 破解干扰爬虫的字体
if not __import__('os').path.isfile('tyc-num.xml'):
    font = TTFont('tyc-num.woff')
    font.saveXML('tyc-num.xml')
ids = BeautifulSoup(open('tyc-num.xml', 'r', encoding='utf-8').read(), 'xml').find('GlyphOrder').find_all('GlyphID')
gid = {}
for g in range(10):  # 主要破解数字0-9
    gid[ids[g + 2]["name"]] = ids[g]["id"]


def aqc_get_company(company_name):  # 爱企查不用登录账号即可流畅查询
    s = requests.session()
    s.headers.update(headers)
    s.get('https://aiqicha.baidu.com/')
    r = s.get(aqc_search_url + parse.urlencode({"q": company_name}))
    if r.ok:
        soup = BeautifulSoup(r.text, "html.parser")
        script = soup.find_all('script')[2].text
        while 'window.pageData' not in script:
            input('可能需要登录才能继续使用!')
        information = json.loads(script[script.find('{'): script.rfind('};') + 1])  # 全部细节
        if "resultList" not in information["result"]:
            return f"未搜寻到公司 “{company_name}” !"
        for info in information["result"]["resultList"]:
            name_ = BeautifulSoup(info["entName"], "html.parser").text.replace('(', '(').replace(')', ')')
            pid = info["pid"]
            if company_name != name_.replace(name_[name_.find('('): name_.rfind(')') + 1], '') and company_name != name_.replace('(', '').replace(')', ''):
                continue
            s.headers["Referer"] = f"{aqc_detail_url}{pid}"
            r = s.get(f'{aqc_data_url}{pid}')
            if r.ok:
                information = r.json()["data"]["basicData"]
                company = {
                    "企业名称": information["entName"],
                    "法定代表人": information["legalPerson"],
                    "经营状态": information["openStatus"],
                    "统一社会信用代码": information["unifiedCode"],
                    "工商注册号": information.get("regCode", ""),
                    "组织机构代码": information["orgNo"],
                    "纳税人识别号": information["taxNo"],
                    "注册资本": information["regCapital"],
                    "实缴资本": information["realCapital"],
                    "登记机关": information["authority"],
                    "成立日期": information["annualDate"],
                    "核准日期": information["annualDate"],
                    "营业期限": information["openTime"],
                    "注册地址": information["regAddr"],
                    "经营范围": information["scope"],
                    "企业类型": information["entType"],
                    "所属行业": information["industry"],
                    "行政区划": information["district"],
                    "参保人数": information["insuranceInfo"]["insuranceNum"],
                    "曾用名": information["prevEntName"]
                }
                return company
            return f"获取公司 “{name_}” 详情信息失败!"
        return f"未搜寻到公司 “{company_name}” !"
    return "搜索失败!"


def tyc_get_company(company_name):  # 天眼查查了几次后就必须要登录查,被天眼查必须登录烦了,lxml 似乎比 html.parser 牛逼
    r = requests.get(tyc_search_url + parse.urlencode({"key": company_name}), headers=headers, cookies={"cookie": tyc_cookie})
    if r.ok:
        soup = BeautifulSoup(r.text, "html.parser")
        table = soup.find("div", attrs={"class": "result-list sv-search-container"})
        if table is None:
            return f"未搜寻到公司 “{company_name}” !"
        for tr in table.find_all("div", attrs={"class": "search-item sv-search-company"}):
            info = tr.find("div", attrs={"class": "content"})
            name_ = info.find("div", attrs={"class": "header"}).find('a').text.replace('(', '(').replace(')', ')')
            url = info.find("div", attrs={"class": "header"}).find('a')["href"]
            if company_name != name_.replace(name_[name_.find('('): name_.rfind(')') + 1], '') and company_name != name_.replace('(', '').replace(')', ''):
                continue
            r = requests.get(url, headers=headers, cookies={"cookie": tyc_cookie})
            if r.ok:
                soup = BeautifulSoup(r.text, "lxml")
                information = soup.find('div', attrs={"id": "_container_baseInfo"}).find('table').find('tbody')
                attrs = {}
                for row in information.find_all('tr'):
                    cols = row.find_all('td')
                    if len(cols) % 2:
                        cols = cols[:-1]
                    for col in range(len(cols) // 2):
                        if cols[col * 2 + 1].find('div', attrs={"class": "name"}):
                            value = cols[col * 2 + 1].find('div', attrs={"class": "name"}).text
                        elif cols[col * 2 + 1].find('span', attrs={"class": "sort-score-value"}):
                            value = cols[col * 2 + 1].find('span', attrs={"class": "sort-score-value"}).text
                        elif cols[col * 2 + 1].find('text', attrs={"class": "tyc-num lh24"}):
                            value = ''
                            for k in cols[col * 2 + 1].find('text', attrs={"class": "tyc-num lh24"}).text:
                                value += gid.get(k, '-')
                        else:
                            value = cols[col * 2 + 1].text
                        attrs[cols[col * 2].find(text=True)] = value
                return attrs
            return f"获取公司 “{name_}” 详情信息失败!"
        return f"未搜寻到公司 “{company_name}” !"
    return "搜索失败!"


if __name__ == '__main__':
    # 公司名示例:浙江阿瓦隆科技有限公司
    print(aqc_get_company(''))
    print(tyc_get_company(""))

  • 3
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
爬虫(Web Crawler)是一种自动化程序,用于从互联网上收集信息。其主要功能是访问网页、提取数据并存储,以便后续分析或展示。爬虫通常由搜索引擎、数据挖掘工具、监测系统等应用于网络数据抓取的场景。 爬虫的工作流程包括以下几个关键步骤: URL收集: 爬虫从一个或多个初始URL开始,递归或迭代地发现新的URL,构建一个URL队列。这些URL可以通过链接分析、站点地图、搜索引擎等方式获取。 请求网页: 爬虫使用HTTP或其他协议向目标URL发起请求,获取网页的HTML内容。这通常通过HTTP请求库实现,如Python中的Requests库。 解析内容: 爬虫对获取的HTML进行解析,提取有用的信息。常用的解析工具有正则表达式、XPath、Beautiful Soup等。这些工具帮助爬虫定位和提取目标数据,如文本、图片、链接等。 数据存储: 爬虫将提取的数据存储到数据库、文件或其他存储介质中,以备后续分析或展示。常用的存储形式包括关系型数据库、NoSQL数据库、JSON文件等。 遵守规则: 为避免对网站造成过大负担或触发反爬虫机制,爬虫需要遵守网站的robots.txt协议,限制访问频率和深度,并模拟人类访问行为,如设置User-Agent。 反爬虫应对: 由于爬虫的存在,一些网站采取了反爬虫措施,如验证码、IP封锁等。爬虫工程师需要设计相应的策略来应对这些挑战。 爬虫在各个领域都有广泛的应用,包括搜索引擎索引、数据挖掘、价格监测、新闻聚合等。然而,使用爬虫需要遵守法律和伦理规范,尊重网站的使用政策,并确保对被访问网站的服务器负责。
Selenium是一个用于自动化浏览器操作的工具,可以模拟用户在浏览器中的行为,例如点击、输入、提交表单等。天是一个提供业信息询的网站,有时候会有反爬虫机制,需要使用Selenium来解决。 以下是使用Selenium进行天爬取的示例代码: ```python from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 创建浏览器实例 driver = webdriver.Chrome() # 打开天网站 driver.get("https://www.tianyancha.com/") # 等待页面加载完成 wait = WebDriverWait(driver, 10) wait.until(EC.presence_of_element_located((By.ID, "home-main-search"))) # 输入搜索关键字 search_input = driver.find_element(By.ID, "home-main-search") search_input.send_keys("公司名称") # 点击搜索按钮 search_button = driver.find_element(By.CLASS_NAME, "search-button") search_button.click() # 等待搜索结果加载完成 wait.until(EC.presence_of_element_located((By.CLASS_NAME, "search-result-single"))) # 获取搜索结果 search_results = driver.find_elements(By.CLASS_NAME, "search-result-single") for result in search_results: print(result.text) # 关闭浏览器 driver.quit() ``` 这段代码使用了Selenium的Chrome驱动来打开天网站,并进行搜索操作。通过等待页面元素加载完成,然后找到相应的元素进行操作,最后获取搜索结果并输出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值