tr、td形式的静态网页爬取-以爬取厦门银行理财产品为例(附代码可实现)

本文主要是介绍tr、td形式的静态网页爬取-以爬取厦门银行理财产品为例(附代码可实现),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目标网页链接:[http://www.xmccb.com/changpinjieshaohh/index.html]
在这里插入图片描述

1.查看网页源代码

在目标网页右击检查,查看网页源代码,目标表格源代码如下:
在这里插入图片描述
*拓展:
tr、td属于HTML语言标签,成对出现,含义如下:
1、tr 标签 ,代表HTML表格中的一行
2、td 标签 , 代表HTML表格中的一个单元格

2.代码分块详解

(1)导入库

import requests
import re
from bs4 import BeautifulSoup
import pandas as pd

Requests库获取网页内容
re库利用正则表达式实现字符串的检索、替换、匹配等操作(正则表达式还需学习
BeautifulSoup库从Html文件中提取数据
pandas库将获取的数据写入文件

(2)对首页的爬取
通过观察目标网页102页的网址,存在以下规律:
第1页(即首页)网址:http://www.xmccb.com/changpinjieshaohh/index.html
第2页网址:
http://www.xmccb.com/changpinjieshaohh/index_2.html
第3页网址:
http://www.xmccb.com/changpinjieshaohh/index_3.html

第102页网址
http://www.xmccb.com/changpinjieshaohh/index_102.html
可以看出,从第二页开始,均在index_后加上页码对应的数字,可通过一个循环爬取2-102的数据,但是第一页后并不是1,故对首页分开处理(能否有统一处理的方式??


headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36'}
#问题1:由于第一页的html不含page,单独运行,可否改进?
link = 'http://www.xmccb.com/changpinjieshaohh/index.html'
start_html = requests.get(link, headers=headers)
start_html.encoding = 'utf-8'  #防止中文乱码
print("第1页响应状态码:", start_html.status_code)
soup = BeautifulSoup(start_html.text, 'lxml')
product = soup.find_all('tr')[6:27]   #soup中find_all方法寻找源代码中的“tr”,目标网页有两个表格,只需定位到第二个表格即可,故选取第6-26
# print(product)
product_list = []
for row in product:    #在每个“tr”中循环找寻“td”productname = row.find_all('td')[0].contentsproductname = str(productname)# print(type(productname1))product_name = re.findall(r'>(.*)<', productname)# print(type(productname2))product_name = str(product_name)[2:-2]# product_name = productname[2:-2]# print(product_name)yieldrate = str(row.find_all('td')[1].contents)[2:-2]productdeadline = str(row.find_all('td')[2].contents)[2:-2]timerange = str(row.find_all('td')[3].contents)[2:-2]deadline = str(row.find_all('td')[4].contents)[2:-2]producttype = str(row.find_all('td')[5].contents)[2:-2]product_list.append({'产品简称':product_name,'预期年化收益率/业绩比较基准':yieldrate,'产品期限(开放周期)':productdeadline,'募集期':timerange,'产品到期日':deadline,'产品类型':producttype})

请求头Headers提供了关于请求、响应或其他发送实体的信息。对于爬虫而言,请求头十分重要,如果没有指定请求头或请求的请求头和实际网页不一致,就可能无法返回正确的结果。
那么,我们如何找到正确的Headers呢?使用Chrome浏览器打开要请求的网页,右击网页任意位置,在弹出的快捷菜单中单击“检查”命令,如图所示,在打开的页面中单击Network选项。
在这里插入图片描述
如下图所示,在左侧的资源中找到需要请求的网页,单击该网页,在右侧就可以看到Headers的详细信息。
在这里插入图片描述
因此,我们可以看到请求头的信息为:
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36

Requests请求访问该网址,并输出响应状态码(status_code),如果返回200,就表示请求成功了;如果返回的是4××,就表示客户端错误;返回5××则表示服务器错误响应。
将代码转换成BeautifulSoup对象:

soup = BeautifulSoup(start_html.text, 'lxml')

这里使用的解析器为“lxml HTML解析器”。
扩展:
print(soup.prettify()) #对代码进行美化

循环语句在每个“tr”里找寻“td”,其中,第一个“td”所对应的产品简称,第二个为预期年化收益率,第三个为产品期限,第四个为募集期,第五个为产品到期日,第六个为产品类型,依次读取到对应的变量中,并保存在列表中。可用正则表达式和字符串的提取规则提取输出内容中我们想要的部分字符串。
(3)对2-102页数据的爬取
这部分的爬取与对首页数据的爬取没有本质区别,只是通过对网址中数字的不同赋值改变所要请求的网址,实现对多个网址内容的依次爬取。

for i in range(2,103):pack_link = 'http://www.xmccb.com/changpinjieshaohh/index_'+str(i)+'.html'page_html = requests.get(pack_link, headers=headers,timeout=10)page_html.encoding = 'utf-8'print(str(i), "页码响应状态码:", page_html.status_code)soup = BeautifulSoup(page_html.text, 'lxml')product = soup.find_all('tr')[6:27]for row in product:productname = row.find_all('td')[0].contentsproductname = str(productname)product_name = re.findall(r'>(.*)<', productname)product_name = str(product_name)[2:-2]yieldrate = str(row.find_all('td')[1].contents)[2:-2]productdeadline = str(row.find_all('td')[2].contents)[2:-2]timerange = str(row.find_all('td')[3].contents)[2:-2]deadline = str(row.find_all('td')[4].contents)[2:-2]producttype = str(row.find_all('td')[5].contents)[2:-2]product_list.append({'产品简称': product_name, '预期年化收益率/业绩比较基准': yieldrate, '产品期限(开放周期)': productdeadline, '募集期': timerange,'产品到期日': deadline, '产品类型': producttype})

3.完整代码

import requests
import re
from bs4 import BeautifulSoup
import pandas as pdheaders = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36'}
#问题1:由于第一页的html不含page,单独运行,可否改进?
link = 'http://www.xmccb.com/changpinjieshaohh/index.html'
start_html = requests.get(link, headers=headers)
start_html.encoding = 'utf-8'
print("第1页响应状态码:", start_html.status_code)
soup = BeautifulSoup(start_html.text, 'lxml')
product = soup.find_all('tr')[6:27]
# print(product)
product_list = []
for row in product:productname = row.find_all('td')[0].contentsproductname = str(productname)# print(type(productname1))product_name = re.findall(r'>(.*)<', productname)# print(type(productname2))product_name = str(product_name)[2:-2]# product_name = productname[2:-2]# print(product_name)yieldrate = str(row.find_all('td')[1].contents)[2:-2]productdeadline = str(row.find_all('td')[2].contents)[2:-2]timerange = str(row.find_all('td')[3].contents)[2:-2]deadline = str(row.find_all('td')[4].contents)[2:-2]producttype = str(row.find_all('td')[5].contents)[2:-2]product_list.append({'产品简称':product_name,'预期年化收益率/业绩比较基准':yieldrate,'产品期限(开放周期)':productdeadline,'募集期':timerange,'产品到期日':deadline,'产品类型':producttype})for i in range(2,103):pack_link = 'http://www.xmccb.com/changpinjieshaohh/index_'+str(i)+'.html'page_html = requests.get(pack_link, headers=headers,timeout=10)page_html.encoding = 'utf-8'print(str(i), "页码响应状态码:", page_html.status_code)soup = BeautifulSoup(page_html.text, 'lxml')product = soup.find_all('tr')[6:27]for row in product:productname = row.find_all('td')[0].contentsproductname = str(productname)product_name = re.findall(r'>(.*)<', productname)product_name = str(product_name)[2:-2]yieldrate = str(row.find_all('td')[1].contents)[2:-2]productdeadline = str(row.find_all('td')[2].contents)[2:-2]timerange = str(row.find_all('td')[3].contents)[2:-2]deadline = str(row.find_all('td')[4].contents)[2:-2]producttype = str(row.find_all('td')[5].contents)[2:-2]product_list.append({'产品简称': product_name, '预期年化收益率/业绩比较基准': yieldrate, '产品期限(开放周期)': productdeadline, '募集期': timerange,'产品到期日': deadline, '产品类型': producttype})# print(product_list)
df = pd.DataFrame(product_list)
# print(df)
columns = ['产品简称','预期年化收益率/业绩比较基准','产品期限(开放周期)','募集期','产品到期日','产品类型']
df.to_csv('G:/网络爬虫/静态网页爬取-厦门银行/result.csv', encoding='utf-8',columns=columns) #写入到csv中

这篇关于tr、td形式的静态网页爬取-以爬取厦门银行理财产品为例(附代码可实现)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/370436

相关文章

网页解析 lxml 库--实战

lxml库使用流程 lxml 是 Python 的第三方解析库,完全使用 Python 语言编写,它对 XPath表达式提供了良好的支 持,因此能够了高效地解析 HTML/XML 文档。本节讲解如何通过 lxml 库解析 HTML 文档。 pip install lxml lxm| 库提供了一个 etree 模块,该模块专门用来解析 HTML/XML 文档,下面来介绍一下 lxml 库

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

活用c4d官方开发文档查询代码

当你问AI助手比如豆包,如何用python禁止掉xpresso标签时候,它会提示到 这时候要用到两个东西。https://developers.maxon.net/论坛搜索和开发文档 比如这里我就在官方找到正确的id描述 然后我就把参数标签换过来

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

poj 1258 Agri-Net(最小生成树模板代码)

感觉用这题来当模板更适合。 题意就是给你邻接矩阵求最小生成树啦。~ prim代码:效率很高。172k...0ms。 #include<stdio.h>#include<algorithm>using namespace std;const int MaxN = 101;const int INF = 0x3f3f3f3f;int g[MaxN][MaxN];int n

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略 1. 特权模式限制2. 宿主机资源隔离3. 用户和组管理4. 权限提升控制5. SELinux配置 💖The Begin💖点点关注,收藏不迷路💖 Kubernetes的PodSecurityPolicy(PSP)是一个关键的安全特性,它在Pod创建之前实施安全策略,确保P