用爬虫爬取以下栏目的前50页中的每页中的公司公告标题,并存储在mysql数据库中。
https://vip.stock.finance.sina.com.cn/corp/view/vCB_BulletinGather.php?page_index=1
以下是Python爬虫代码示例,用于爬取新浪财经公司公告栏目前50页的公告标题,并将其存储在MySQL数据库中。请注意,在运行该代码之前,需要事先安装并配置好Python的相关库和MySQL数据库。
import requests
import re
import pymysql
# 定义MySQL数据库连接信息
mysql_config = {
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': 'password',
'db': 'testdb',
'charset': 'utf8mb4',
'cursorclass': pymysql.cursors.DictCursor
}
# 定义正则表达式
title_pattern = re.compile(r'<a href="(.*?)".*?>(.*?)<\/a>')
# 定义爬虫函数
def spider(page):
# 构造URL
url = 'https://vip.stock.finance.sina.com.cn/corp/view/vCB_BulletinGather.php?page_index=' + str(page)
# 发送HTTP请求
response = requests.get(url)
# 解析HTML页面
html = response.text
# 查找公司公告标题
titles = title_pattern.findall(html)
# 存储公司公告标题到MySQL数据库中
connection = pymysql.connect(**mysql_config)
try:
with connection.cursor() as cursor:
for title in titles:
# 插入标题到MySQL数据库中
sql = "INSERT INTO `announcements` (`title`) VALUES (%s)"
cursor.execute(sql, (title[1]))
# 提交事务
connection.commit()
finally:
# 关闭数据库连接
connection.close()
# 爬取前50页的公司公告
for page in range(1, 51):
spider(page)
该代码将爬取新浪财经公司公告栏目前50页的公告标题,并将其存储在名为“announcements”的MySQL数据库表中。请根据需要修改MySQL数据库连接信息和其他配置。
看到了应届生求职网站里面发布了众多的全国各省各市的求职信息,可以看到各个公司的岗位需求,以及招聘时间,地区等等,感觉挺丰富的,然后顺便练一下爬虫,来获取哈信息的,不是去来求职的哈哈,当然里面的求职信息也是值得我们关注的。
此次爬取的信息
步骤如下:
导入所需要的库,包括 requests、pymysql、BeautifulSoup等。建立数据库连接。
定义爬取函数 get_title,主要实现如下:
a. 遍历各个页面(使用 getUrls 函数得到每个页面的 URL)。
b. 在每个页面上运行 parsePage 函数,解析得到标题等信息。
c. 将解析出来的信息插入 MySQL 数据库中。
a. 使用 BeautifulSoup 库抓取页面信息。
b. 使用正则表达式筛选出需要的标题、作者、发表时间和摘要信息。
c. 将筛选出来的信息存入列表中。
代码如下:
import re
import requests
import pymysql
from bs4 import BeautifulSoup
# 数据库连接配置
DB_SETTINGS = {
"host": "localhost",
"port": 3306,
"user": "root",
"password": "yourpassword",
"db": "yourdb",
}
# 定义获得文章 URL 的函数
def getUrls():
all_items = 12 * 2 + 1
urls = []
partstr = "http://crad.ict.ac.cn/CN/volumn/volumn_"
for i in range(all_items + 1):
strone = partstr + str(1300 + i) + ".shtml"
urls.append(strone)
for url in urls:
yield url
# 定义解析函数
def parsePage(infoList, html):
soup = BeautifulSoup(html, "html.parser")
# 解析文章标题
item = soup(name='a', attrs={"class": "biaoti"})
biaoti = re.findall(r'target="_blank">(.*?)</a', str(item), re.S)
# 解析文章作者
item = soup(name='dd', attrs={"class": "zuozhe"})
zuozhe = re.findall(r'class="zuozhe">(.*?)</dd', str(item), re.S)
# 解析发表时间信息
item = soup(name='dd', attrs={"class": "kmnjq"})
fanwei = re.findall(r'class="kmnjq">(.*?)<', str(item), re.S)
fanwei = re.sub('[\r\n\t\xa0]', '', ''.join(fanwei))
fanwei = re.sub('doi:', '', ''.join(fanwei))
fanwei = fanwei.split('.')
# 解析摘要信息
item = soup(name='div', attrs={"class": "white_content zhaiyao"})
zhaiyao = re.findall(r'">(.*?)</div', str(item), re.S)
# 将信息添加到列表中
for i in range(len(biaoti)):
global count # 全局变量,用于统计总爬取数据条数
infoList.append((count, biaoti[i], zuozhe[i], fanwei[i], zhaiyao[i]))
count += 1
# 定义主函数
def get_title():
# 连接 MySQL 数据库
conn = pymysql.connect(**DB_SETTINGS)
cursor = conn.cursor()
# 创建 paperinfo表
cursor.execute("""
CREATE TABLE IF NOT EXISTS `paperinfo` (
`序号` INT(0) NOT NULL,
`标题` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`作者` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`年,月,页码` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`摘要` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`序号`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci ROW_FORMAT=DYNAMIC
""")
# 调用 getUrls 函数获取所有文章 URL
urls = getUrls()
# 循环遍历每个 URL,并解析获取标题等信息,存入 MySQL 数据库中
for url in urls:
try:
r = requests.get(url)
r.encoding = 'utf-8'
infoList = []
global count
count = 1
parsePage(infoList, r.text)
for info in infoList:
cursor.execute(f"""
INSERT INTO paperinfo(序号, 标题, 作者, `年,月,页码`, 摘要)
VALUES({info[0]}, "{info[1]}", "{info[2]}", "{info[3]}", "{info[4]}")
""")
conn.commit()
print(f'{url} 提交完成')
except Exception as e:
print(f'{url} 获取失败')
print(e)
# 关闭数据库连接
cursor.close()
conn.close()
# 调用主函数
get_title()