一.代码展示
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pymysql
def GetContent():
# 发出请求,获取html
# 这里使用《环境法》作为例子
html = urlopen("https://www.mee.gov.cn/ywgz/fgbz/fl/201404/t20140425_271040.shtml")
# 将其转化为字符串
html_text = bytes.decode(html.read())
# 使用BeautifulSoup选取需要的内容
soup=BeautifulSoup(html_text,features="lxml")
# 观察可知法律条文都在p标签中
content=soup.findAll("p")
return content
def insert(content):
db = pymysql.connect("localhost", "root", "****", "name")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
mainmsg="'"
excmsg="'"
for ind,i in enumerate(content):
# 用最笨的方法检查
# 求大佬指点
if '章' not in i.text:
if '第'and'条' in i.text:
mainmsg="'"
mainmsg+=i.text
excmsg="'"
if '第'and'条' not in i.text:
excmsg+=i.text
if ind < len(content)-1:
if '第'and'条' in content[ind+1].text:
mainmsg+="'"
excmsg+="'"
sql="insert into 法条(main, extra) values("+mainmsg+","+excmsg+")"
print(sql)
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback()
def main():
content=GetContent()
insert(content)
if __name__=='__main__':
main()
二.运行结果
三.主要问题
1)如何识别法条
使用BeautifulSoup美化后的content还是有很多赘余的内容
观察发现法条的格式基本为
第x条 ___第一句__
(__其他__)
第x+1条 ___第一句__
(__其他__)
....
于是可以想到使用if语句
大致思路:
首先排除标题也就是有“章”以及在第一条之前的内容
然后对法条:
如果第i条中有“第**条”那么这一条就是main
如果第i条中没有“第**条”那么这一条就是extra
如果第i+1条中有“第**条”那么这一段法条结束了
if '章' not in i.text:
if '第'and'条' in i.text:
mainmsg="'"
mainmsg+=i.text
excmsg="'"
if '第'and'条' not in i.text:
excmsg+=i.text
if ind < len(content)-1:
if '第'and'条' in content[ind+1].text:
mainmsg+="'"
excmsg+="'"
sql="insert into 法条(main, extra) values("+mainmsg+","+excmsg+")"
因此可以得到数据库格式:
使用main存放第一句,使用extra存放其他几句
这里可以优化一下,把“第**条”另开一列放,大致思路是
index=i.text.find("第")
first=i.text[:index]
second=i.text[index:]
但是我懒得写
∠( ᐛ 」∠)_
2)如何写入数据库
相比获取法条,将数据插入数据库较为简单
回想一下法条的格式
第**条 main
(extra)
第**+1条 main
(extra)
也就是说如果下一句中包含“第**条”就可以将当前条写入
sql="insert into 法条(main, extra) values("+mainmsg+","+excmsg+")"
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback()
***相比