Python 爬取企查查数据

由于工作需要,爬取企查查数据,在前人的基础上做了修改,可以爬全部的数据。

首先你的电脑上要已经安装了Python,在此基础上安装request模块,lxml模块,BeautifulSoup模块和xlwt模块,具体介绍可参照:https://my.oschina.net/u/3629884/blog/1532275

代码如下:

#-*- coding-8 -*-
import requests
import lxml
from bs4 import BeautifulSoup
import xlwt


def craw(url,key_word):
    User_Agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0'
    headers = {

'Host':'www.qichacha.com',

'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Connection': 'keep-alive',
'User-Agent':r'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0',
'Cache-Control': 'max-age=0',
'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Accept-Encoding':'gzip, deflate',
'Referer': 'http://www.qichacha.com/search?key='+key_word,
'Cookie':r'zg_did=%7B%22did%22%3A%20%2215fa403cb9d15f-036a7756df6645-173b7740-100200-15fa403cb9e2c6%22%7D; zg_de1d1a35bfa24ce29bbf2c7eb17e6c4f=%7B%22sid%22%3A%201510617843749%2C%22updated%22%3A%201510626410277%2C%22info%22%3A%201510285233062%2C%22superProperty%22%3A%20%22%7B%7D%22%2C%22platform%22%3A%20%22%7B%7D%22%2C%22utm%22%3A%20%22%7B%7D%22%2C%22referrerDomain%22%3A%20%22www.baidu.com%22%2C%22cuid%22%3A%20%22f62f1e8a5eaa98a4fdd7be63f003baf3%22%7D; UM_distinctid=15fa403d33a86-04e900fd4e3572-173b7740-100200-15fa403d33b3d; CNZZDATA1254842228=770755339-1510283630-https%253A%252F%252Fwww.baidu.com%252F%7C1510623074; _uab_collina=151028523773154434859974; _umdata=2BA477700510A7DFF3E360D067D6CBF26EBF4D0B7616E2F668ACF5B05BA3A15BB7B2A5C9048062DECD43AD3E795C914C698D4F63619694FD3C24BCCF0E0016EF; PHPSESSID=tm27c7utiff9j5iqbh4g1cg0l5; acw_tc=AQAAAIyPMmgK2AUA4oumtwogJ3fbLlic; hasShow=1',
'Cache-Control':'no-cache',

}
    response = requests.get(url,headers = headers)
    if response.status_code != 200:
        response.encoding = 'utf-8'
        print(response.status_code)
        print('ERROR')    
    soup = BeautifulSoup(response.text,'lxml')
    #print(soup)
    com_names = soup.find_all(class_='ma_h1')#获取公司名称
    #print(com_names)
    #com_name1 = com_names[1].get_text()
    #print(com_name1)
    peo_names = soup.find_all(class_='a-blue')#公司法人
    #print(peo_names)
    peo_phones = soup.find_all(class_='m-t-xs')#公司号码
    #tags = peo_phones[4].find(text = True).strip()
    #print(tags)
    #tttt = peo_phones[0].contents[5].get_text()
    #print (tttt)
    #else_comtent = peo_phones[0].find(class_='m-l')
    #print(else_comtent)
    #peo_emails=soup.find_all(class_='m-1')
    global com_name_list
    global peo_name_list
    global peo_phone_list
    global com_place_list
    global zhuceziben_list
    global chenglishijian_list
    global email_list
    print('开始爬取数据,请勿打开excel')
    for i in range(0,len(com_names)):
        n = 1+3*i
        m = i+2*(i+1)
        try:
            peo_phone = peo_phones[n].find(text = True).strip()
            com_place = peo_phones[m].find(text = True).strip()
            zhuceziben = peo_phones[3*i].find(class_='m-l').get_text()
            chenglishijian = peo_phones[3*i].contents[5].get_text()
            email=peo_phones[n].contents[1].get_text()
        
        #print('email',email)
            peo_phone_list.append(peo_phone)
            com_place_list.append(com_place)   
            zhuceziben_list.append(zhuceziben)
            chenglishijian_list.append(chenglishijian)
            email_list.append(email)
        except Exception:
            print('exception')

    for com_name,peo_name in zip(com_names,peo_names):
        com_name = com_name.get_text()
        peo_name = peo_name.get_text()
        com_name_list.append(com_name)
        peo_name_list.append(peo_name)
        
    

        
if __name__ == '__main__':
    com_name_list = []
    peo_name_list = []
    peo_phone_list = []
    com_place_list = []
    zhuceziben_list = []
    chenglishijian_list = []
    email_list=[]

    key_word = input('请输入您想搜索的关键词:')
    print('正在搜索,请稍后')
    for x in range(400,500):
        if x==1:
            url = r'http://www.qichacha.com/search?key={}#p:{}&'.format(key_word,x)
        else:
            url=r'http://www.qichacha.com/search_index?key={}&ajaxflag=1&p={}&'.format(key_word,x)
        #url = r'http://www.qichacha.com/search?key={}#p:{}&'.format(key_word,x)
        s1 = craw(url,key_word.encode("utf-8").decode("latin1"))
    workbook = xlwt.Workbook()
    #创建sheet对象,新建sheet
    sheet1 = workbook.add_sheet('xlwt', cell_overwrite_ok=True)
    #---设置excel样式---
    #初始化样式
    style = xlwt.XFStyle()
    #创建字体样式
    font = xlwt.Font()
    font.name = 'Times New Roman'
    font.bold = True #加粗
    #设置字体
    style.font = font
    #使用样式写入数据
    # sheet.write(0, 1, "xxxxx", style)
    print('正在存储数据,请勿打开excel')
    #向sheet中写入数据
    name_list = ['公司名字','法定代表人','联系方式','注册人资本','成立时间','公司地址','公司邮件']
    for cc in range(0,len(name_list)):
        sheet1.write(0,cc,name_list[cc],style)
    for i in range(0,len(com_name_list)):
        sheet1.write(i+1,0,com_name_list[i],style)#公司名字
        sheet1.write(i+1,1,peo_name_list[i],style)#法定代表人
        sheet1.write(i+1,2,peo_phone_list[i],style)#联系方式
        sheet1.write(i+1,3,zhuceziben_list[i],style)#注册人资本
        sheet1.write(i+1,4,chenglishijian_list[i],style)#成立时间
        sheet1.write(i+1,5,com_place_list[i],style)#公司地址
        sheet1.write(i+1,6,email_list[i],style)#邮件地址
    #保存excel文件,有同名的直接覆盖
    workbook.save(r'E:\test.xls')
    print('the excel save success')




代码执行结果如下:

  • 3
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
### 回答1: 要使用Python爬取企查查数据,可以按照以下步骤进行操作: 1. 导入所需的Python库,如requests、beautifulsoup和pandas。 ``` import requests from bs4 import BeautifulSoup import pandas as pd ``` 2. 构造请求URL,可以通过企查查网站检索得到相应公司的URL,或者直接拼接URL。 ``` url = "https://www.qichacha.com/company_search?key=关键词" ``` 3. 发送HTTP请求,获取网页内容。 ``` headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"} response = requests.get(url, headers=headers) ``` 4. 使用BeautifulSoup解析网页内容,提取所需数据。 ``` soup = BeautifulSoup(response.text, 'html.parser') # 定位到要提取的数据的HTML标签 data = soup.find_all('div', class_='search_list')[0].find_all('tr') ``` 5. 将提取的数据存储到DataFrame中,方便后续处理和分析。 ``` records = [] for tr in data: record = [] for td in tr.find_all('td'): record.append(td.text.strip()) records.append(record) df = pd.DataFrame(records) ``` 6. 对DataFrame进行必要的数据清洗和处理。 ``` df.columns = df.iloc[0] # 将第一行作为列名 df = df[1:] # 去除第一行数据 ``` 7. 可以选择将处理后的数据保存到本地文件,或者进行进一步的分析和可视化展示。 ``` df.to_csv('企查查数据.csv', index=False) ``` 注意:爬取网站数据要遵守相关法律法规和网站的使用条款,尊重网站规则并使用爬虫技术进行合法合规的数据获取。 ### 回答2: Python可以使用多种库进行网页数据爬取,其中比较常用的是BeautifulSoup和Selenium。 首先,我们需要安装相应的库,可以使用pip install进行安装。 ```python pip install beautifulsoup4 pip install selenium ``` 然后,我们需要导入所需的库。 ```python from selenium import webdriver from bs4 import BeautifulSoup import time ``` 接着,我们需要设置webdriver的路径,并实例化一个浏览器对象。 ```python # 设置webdriver的路径 driver_path = "chromedriver_path/chromedriver" # 实例化一个浏览器对象,这里以Chrome为例 browser = webdriver.Chrome(executable_path=driver_path) ``` 接下来,我们需要打开企查查的网页并进行相关操作,这里以搜索公司信息为例。 ```python # 打开企查查网页 url = "https://www.qcc.com" browser.get(url) # 找到搜索框并输入关键词 search_input = browser.find_element_by_id("headerKey") search_input.send_keys("公司名") # 找到搜索按钮并点击 search_button = browser.find_element_by_id("index-getData") search_button.click() # 等待页面加载 time.sleep(5) ``` 页面加载完成后,我们可以通过BeautifulSoup来解析所需的数据。 ```python # 获取页面源代码 page_source = browser.page_source # 使用BeautifulSoup解析数据 soup = BeautifulSoup(page_source, "html.parser") # 找到所需的数据,并进行相应的处理 data = soup.find_all("div", class_="result-list") ``` 最后,我们需要关闭浏览器。 ```python browser.quit() ``` 这样,我们就完成了使用Python爬取企查查数据的过程。可以根据需求对代码进行相应的修改和优化。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值