同时将获取的数据保存在自己的数据库中
时间: 2023-11-27 13:03:12 浏览: 39
以下是一个基于Python的爬虫代码,可以获取PubChem中的熔点数据,并将数据保存到MySQL数据库中:
```
import requests
from bs4 import BeautifulSoup
import mysql.connector
# 定义需要查询的化学品名称或CAS号
query = "benzene"
# 构造查询URL
url = f"https://pubchem.ncbi.nlm.nih.gov/compound/{query}#section=Melting-Point"
# 发送HTTP请求
response = requests.get(url)
# 使用Beautiful Soup解析HTML
soup = BeautifulSoup(response.text, "html.parser")
# 查找熔点数据
mp_data = soup.find("div", {"id": "Melting-Point"}).find("span", {"class": "value"}).text
# 连接MySQL数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 插入熔点数据到MySQL数据库
mycursor = mydb.cursor()
sql = "INSERT INTO mp_data (compound, melting_point) VALUES (%s, %s)"
val = (query, mp_data)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
```
在这个代码中,我们首先定义需要查询的化学品名称或CAS号,然后构造查询URL,并发送HTTP请求。使用Beautiful Soup解析HTML页面,我们可以通过查找特定的HTML元素,获取其中的熔点数据。然后使用mysql.connector库连接MySQL数据库,并将熔点数据插入到指定的数据表中。
需要注意的是,这个代码只是一个简单的例子,实际上爬取PubChem网站数据需要遵循相关规定和条款,不能违反法律法规和道德规范。同时,由于网站数据更新和变化可能会导致数据不准确或失效,因此需要进行数据的验证和处理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)