【爬虫】使用beautifulsoup、requests爬取网页上的图片;循环爬取上市公司高管信息

**声明:本篇博文只用于对于爬虫技术的学习交流。如果侵犯到相关网站利益,请联系我删除博文。造成不便还请见谅。希望各位同学在学习的时候不要过于频繁的去请求。

最近博主在学习前端开发和网页相关的东西,这些知识和网络爬虫(特别是网页爬取)有很强的联系,然后突然发现爬虫也有很多有趣的地方,所以准备开始系统性地把爬虫那几个包都学一学,用一用。本文展示了两个爬虫案例;意识使用beautifulsoup和requests包对网站的图片进行爬取,并保存到本地;二是从网站循环爬取上市公司高管信息。

目录

1 图片爬取

1.1 背景任务概述

1.2 代码实现

2 从网站循环爬取上市公司高管信息

2.1 任务背景

2.2 过程和代码实现


1 图片爬取

1.1 背景任务概述

  • 利用爬虫将该网页的所有头像类别中的头像文件获取并保存。
  • 分不同文件夹保存,每个类别单独建立文件夹,然后将该类别内所有头像图片爬取并保存在文件夹中;
  • 文件夹命名用原类别名称,图片名截取原图片名中的四个字符;
  • 原类别名称中存在的不能用于文件夹命名的非法字符用‘0’代替;

1.2 代码实现

说明:

使用request.get()函数获取网页的源码;

使用beautifulsoup()对网页源码进行解析(解析成树结构);

使用soup.select()函数对网页中的元素进行CSS定位;

步骤:

如何获取网页元素中的CSS定位

建立文件夹和保存文件时首先判断是否在当前文件夹已经存在要建立的文件夹或文件;

# 导入必要的包
from bs4 import BeautifulSoup
import requests
import os

#使用request取到网页的源码
html = requests.get(r"https://www.woyaogexing.com/touxiang/weixin/")
html.encoding = 'utf-8'

#使用beautifulsoup对网页源码进行解析
soup = BeautifulSoup(html.text,'lxml')

#使用css定位相应语句
image_types = soup.select("#main > div.list-main.mt10.cl > div.list-left.z > div.pMain > div> a.imgTitle")
#创建一级文件夹
newdir = os.getcwd()+r"\爬取图片"
if not os.path.exists(newdir):
    os.mkdir(newdir)
for image_type in image_types:
    #创建二级文件夹(将非法字符替换为0)
    if not os.path.exists((newdir+'\\' +image_type.get_text()).replace(' ','0').replace('/','0').replace('?','0')):
        os.mkdir((newdir+'\\' +image_type.get_text()).replace(' ','0').replace('/','0').replace('?','0'))
    #获取图片地址并保存图片
    html_temp = requests.get(r"https://www.woyaogexing.com" + image_type['href'])
    html_temp.encoding = 'utf-8'
    soup_temp = BeautifulSoup(html_temp.text,'lxml')
    images = soup_temp.select('#main > div.contMain.mt10 > div.contLeft.z > div.contLeftA > ul > li > a > img')
    for image in images:
        path = (newdir+'\\' + image_type.get_text() +'\\'+ image['src'].split('/')[-1][0:4] + '.jpg').replace(' ','0').replace('/','0').replace('?','0')
        r = requests.get('http:'+image['src'])
        r.raise_for_status()
        with open(path,'wb') as f:
            f.write(r.content)
            f.close()
            print("保存成功",(image_type.get_text() +'\\'+ image['src'].split('/')[-1][0:4] + '.jpg').replace(' ','0').replace('/','0').replace('?','0'))

结果展示:

 

 

2 从网站循环爬取上市公司高管信息

2.1 任务背景

从tushare获取若干上市公司代码列表,观察新浪财经网站的各个上市公司网页URL的规律,并构建循环爬虫,抓取网页源代码,通过XPath提取每条任职信息中高管的姓名、职务、起始日期、终止日期。

2.2 过程和代码实现

1、导入需要的包:

import requests
from lxml import etree
import tushare as ts
import pandas as pd

 2、从tushare获取上市企业信息(主要利用上市代码):

mytoken="744f361bc4c1762cd87f0f034ae0a6a5c6de4e2b702e484dc195b3c1"
ts.set_token(mytoken)#设置tushare token
pro = ts.pro_api()#初始化接口
df = pro.stock_basic(exchange='', list_status='L', fields='symbol,name,area,industry,list_date')#获取股票列表数据
stock_sample = df.sample(axis = 0, n = 10)#随机获取十家公司的信息作为爬取对象公司
stock_sample#展示抽取的十家公司

 3、观察网页URL:

秦川机床高管信息网页:http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_CorpManager/stockid/000837.phtml

迎丰股份高管信息网页:

 http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_CorpManager/stockid/605055.phtml

浦发银行高管信息网页:

http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_CorpManager/stockid/600000.phtml

可以发现每一家公司的这一网页的url前面部分都是相同的,只有后面的数字(公司代码)有所区别,所以我们可以在爬取的时候通过改变后面的数字(公司代码)而访问到不同的信息网页。

 4、设置公司都相同的hearder信息和网页上所需信息的Xpath:

#设置所有公司都相同的header信息
headers = {
    "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "Accept-Encoding":"gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cache-Control":"max-age=0",
    "Connection":"keep-alive",
    "Host":"vip.stock.finance.sina.com.cn",
    "Upgrade-Insecure-Request":"1",
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36"
}
#设置Xpath
name_xpath = "/html/body/div[@class='wrap main_wrap clearfix']/div[@class='R']/div[@id='con02-6']/table[@id='comInfo1']/tbody/tr/td[@class='ccl'][1]/div/a"
job_xpath = "/html/body/div[@class='wrap main_wrap clearfix']/div[@class='R']/div[@id='con02-6']/table[@id='comInfo1']/tbody/tr/td[@class='ccl'][2]/div"
starttime_xpath = "/html/body/div[@class='wrap main_wrap clearfix']/div[@class='R']/div[@id='con02-6']/table[@id='comInfo1']/tbody/tr/td[@class='ccl'][3]/div"
endtime_xpath = "/html/body/div[@class='wrap main_wrap clearfix']/div[@class='R']/div[@id='con02-6']/table[@id='comInfo1']/tbody/tr/td[@class='ccl'][4]/div"
all_name = []
all_job = []
all_starttime = []
all_endtime = []
all_stkid = []
all_stkid_output = []
all_stkname = []
all_stkname_output = []

步骤:

hearder查询和Xpath查询

5、开始循环爬取:

###########循环爬取信息开始
all_stkid = stock_sample.symbol.tolist()#将dataframe数据中的代码部分转化为list
all_stkname = stock_sample.name.tolist()#将dataframe数据中的公司名字部分转化为list
for i in range(0,len(all_stkid)):
    #输出提示信息
    print("正在爬取的公司为             "+ all_stkname[i] + "           公司代码是           " + all_stkid[i] )
    url = "http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_CorpManager/stockid/" + all_stkid[i] + ".phtml"
    print("网址是" + url)
    html = requests.get(url, headers = headers)#取得网页内容
    html.encoding = "gb18030"#设置字符编码
    tree = etree.HTML(html.text)#建立树
    #使用xpath进行解析
    name_list = tree.xpath(name_xpath)
    job_list = tree.xpath(job_xpath)
    starttime_list = tree.xpath(starttime_xpath)
    endtime_list = tree.xpath(endtime_xpath)
    #print(name_list)
    #print(job_list)

    #存入list中
    name_list = [name.text for name in name_list]
    all_name.extend(name_list)
    job_list = [job.text for job in job_list]
    all_job.extend(job_list) 
    starttime_list = [starttime.text for starttime in starttime_list]
    all_starttime.extend(starttime_list)
    endtime_list = [endtime.text for endtime in endtime_list]
    all_endtime.extend(endtime_list)
    all_stkid_output.extend([all_stkid[i]]*len(name_list))
    all_stkname_output.extend([all_stkname[i]]*len(name_list))

6、保存到dataframe中并输出到Excel:

#生成输出的字典
data = {
    "股票代码":all_stkid_output,
    "股票名称":all_stkname_output,
    "姓名":all_name,
    "职务":all_job,
    "起始时间":all_starttime,
    "离任时间":all_endtime
}
df = pd.DataFrame(data)

#输出到Excel
path = "新浪财经高管任职10家随机.xlsx"
df.to_excel(path)

7、结果:

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值