爬虫项目-人大法律文件

写在前面的话:

爬虫是一个高效的信息收集手段,但同时其对服务器也会造成一定的负担,因此希望在设计爬虫脚本时,希望大家有意的增加爬虫时间间隔,维护一个良好的网络环境。

这个项目是我自己的百度AI Studio上的项目,目的是想要自己做数据库,进行法律文件的实时查询。

项目思路:

1.引用相关的包:bs4(用于规范化html文件)、urllib(用于访问服务器)、time(用于添加各种时间和等待)

2.定义文件保存函数:包含错误信息保存(用于查看哪个法律文件没有保存)、保存文件列表、保存文件。

3.获取法律文件列表,并保存

4.依据法律文件列表获取法律文件内容,并保存

项目代码:

1.引用所需要的库:

from bs4 import BeautifulSoup
from urllib import request
import time

2.定义保存相关信息的函数

# 保存页面读取错误信息
def save_ErrorData(str_error):
    with open('save/record.txt',mode='a') as file:
        file.write(str_error)

# 保存文件名称集合
def save_FileNames(str_FileName):
    with open('save/filenames.txt',mode='a') as file:
        file.write(str_FileName)

# 保存相关文件内容
def save_File(str_FileName,str_FileData):
    with open('save/'+str_FileName+'.txt',mode='w',encoding='utf-8') as file:
        file.write(str_FileData)

3.定义被爬取网站的基础网址

str_URL_base='http://www.npc.gov.cn/'

4.爬取第一个页面,主要用于测试代码

str_URL='http://www.npc.gov.cn/npc/c12488/list.shtml'
req = request.Request(url=str_URL)
print(req)
res = request.urlopen(req).read()
soup=BeautifulSoup(res,'html.parser')
# print(soup)
soup_clist=soup.find_all(name='ul',class_='clist')
print('-----------------------------------------------------')
# print(soup_clist)
if(soup_clist==[]):
    save_ErrorData('not save layer no:'+str(0)+'\n')
    print('error occured:0')
else:
    for temp in soup_clist:
        soup_clist_a=temp.find_all(name='a')
        for temp_1 in soup_clist_a:
            print(temp_1['href'],temp_1.string)
            save_FileNames(temp_1.string+'---'+'http://www.npc.gov.cn'+temp_1['href']+'\n')

5.爬取其他法律列表页面,获取所有法律文件标题和URL。一定要添加time.sleep(),已减小服务器负担。

for i in range(2,16,1):
    temp_strURL='http://www.npc.gov.cn/npc/c12488/list_'+str(i)+'.shtml'
    req = request.Request(url=temp_strURL)
    res = request.urlopen(req).read()
    soup = BeautifulSoup(res, 'html.parser')
    soup_clist = soup.find_all(name='ul', class_='clist')
    # print(soup_clist)
    if (soup_clist == []):
        save_ErrorData('not save layer no:' + str(0) + '\n')
        print('error occured:'+str(i))
    else:
        for temp in soup_clist:
            soup_clist_a = temp.find_all(name='a')
            for temp_1 in soup_clist_a:
                print(temp_1['href'], temp_1.string)
                save_FileNames(temp_1.string + '---' + 'http://www.npc.gov.cn/' + temp_1['href'] + '\n')
    time.sleep(3)  #睡眠3秒,以防过度爬取导致他人访问网站堵塞

6.访问各个法律文件所在网址,保存各个法律文件。一定要添加time.sleep(),已减小服务器负担。

with open('save/filenames.txt','r',encoding='utf-8') as file_temp:
    info_list=file_temp.readlines()
    # print(info_list)
    for info_temp in info_list:
        name,url=info_temp.split('---')
        print(name,url)
        try:
            req = request.Request(url=url)
            res = request.urlopen(req).read()
            soup=BeautifulSoup(res,'html.parser')
            # print(soup)
            div=soup.find('div',id='Zoom')
            # print(div)
        except BaseException as e:
            print('error occur:', e)
            save_ErrorData(time.strftime('%Y%m%d%H%M%S') + '未获取文件:' + name + '。error detail:' + str(e) + '\n')
        try:
            str_content=div.get_text()
            # print(str_content)
            save_File(name,str_content)
        except BaseException as e:
            print('error occur:',e)
            save_ErrorData(time.strftime('%Y%m%d%H%M%S')+'未获取文件:'+name+'。error detail:'+str(e)+'\n')
        time.sleep(2)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
感谢您的提问。我理解您想了解如何用 Python 爬虫来爬取雪球网的金融数据。下面是一个简单的爬虫项目,可以帮助您实现这个目标: 1. 确定爬取的目标网页 我们需要确定要爬取的目标网页。在本例中,我们将使用雪球网的金融数据页面:https://xueqiu.com/hq。 2. 使用 requests 库发送 HTTP 请求 我们可以使用 Python 的 requests 库来发送 HTTP 请求并从目标网页获取数据。以下是如何发送 GET 请求的示例代码: ```python import requests url = 'https://xueqiu.com/hq' response = requests.get(url) print(response.text) ``` 3. 解析 HTML 页面 我们可以使用 Python 的 Beautiful Soup 库来解析 HTML 页面。以下是如何使用 Beautiful Soup 库解析响应的 HTML 页面的示例代码: ```python from bs4 import BeautifulSoup soup = BeautifulSoup(response.text, 'html.parser') # 打印解析后的 HTML 页面 print(soup.prettify()) ``` 4. 提取数据 一旦我们成功解析了 HTML 页面,就可以使用 Beautiful Soup 库中的一些方法来提取我们需要的数据。以下是如何从 HTML 页面中提取股票代码和股票名称的示例代码: ```python # 找到包含股票代码和名称的表格 table = soup.find('table', {'class': 'table'}) # 找到所有的行 rows = table.find_all('tr') # 遍历每一行,并提取股票代码和名称 for row in rows: cols = row.find_all('td') if len(cols) > 0: code = cols[0].text.strip() name = cols[1].text.strip() print(code, name) ``` 5. 存储数据 最后,我们可以将提取的数据存储到文件中。以下是如何将股票代码和名称存储到 CSV 文件中的示例代码: ```python import csv with open('stocks.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['Code', 'Name']) for row in rows: cols = row.find_all('td') if len(cols) > 0: code = cols[0].text.strip() name = cols[1].text.strip() writer.writerow([code, name]) ``` 希望这个爬虫项目可以帮助您了解如何用 Python 爬虫来爬取雪球网的金融数据。如果您还有其他问题,请随时问我。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值