怎么用python爬取网页中大学排名并导入数据库
时间: 2023-12-23 10:06:22 浏览: 31
首先,需要使用 Python 中的 requests 库和 BeautifulSoup 库来获取网页内容和解析 HTML。接下来,可以使用正则表达式或 BeautifulSoup 对网页内容进行筛选和提取,得到所需的大学排名信息。最后,使用 Python 中的数据库模块(如 pymysql 或 sqlite3)将数据导入数据库中。
以下是简单的代码示例:
```python
import requests
from bs4 import BeautifulSoup
import pymysql
# 获取网页内容
url = 'http://www.example.com/university_ranking.html'
response = requests.get(url)
html = response.text
# 解析 HTML
soup = BeautifulSoup(html, 'html.parser')
# 筛选和提取信息
table = soup.find('table', {'id': 'ranking'})
rows = table.find_all('tr')[1:]
data = []
for row in rows:
cols = row.find_all('td')
name = cols[0].text.strip()
rank = cols[1].text.strip()
location = cols[2].text.strip()
data.append((name, rank, location))
# 将数据导入数据库
conn = pymysql.connect(host='localhost', user='root', password='password', database='db_name')
cursor = conn.cursor()
for d in data:
cursor.execute('INSERT INTO university_ranking (name, rank, location) VALUES (%s, %s, %s)', d)
conn.commit()
cursor.close()
conn.close()
```
需要注意的是,具体的代码实现可能会因为网页结构和数据库类型等不同而有所不同,需要根据实际情况进行调整。此外,爬取网页时需要遵守网站相关规定,不得进行恶意爬取和滥用。