用python编程将所输入的网站进行数据爬取(例如标题与链接),并将所爬取到的内容存入数据库中
时间: 2024-04-07 15:28:10 浏览: 13
好的,这是一个比较常见的数据爬取任务,需要用到Python中的requests、BeautifulSoup和pymysql三个库。
首先,我们需要使用requests库发送HTTP请求获取到网页的HTML代码,然后使用BeautifulSoup库解析HTML代码,提取出我们需要的数据(例如标题和链接),最后将数据存入数据库中。
以下是一个简单的代码示例,假设我们要爬取的网站是https://www.example.com:
```python
import requests
from bs4 import BeautifulSoup
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', user='root', password='password', database='test', charset='utf8mb4')
cursor = db.cursor()
# 发送HTTP请求获取网页内容
url = 'https://www.example.com'
response = requests.get(url)
html = response.text
# 使用BeautifulSoup解析HTML代码
soup = BeautifulSoup(html, 'html.parser')
titles = soup.find_all('a') # 找到所有链接
for title in titles:
title_text = title.text # 获取链接文本
link = title['href'] # 获取链接地址
# 将数据存入数据库
sql = "INSERT INTO `example` (`title`, `link`) VALUES (%s, %s)"
cursor.execute(sql, (title_text, link))
db.commit()
# 关闭数据库连接
db.close()
```
需要注意的是,以上代码只是一个简单示例,实际情况中需要根据具体网站的HTML代码进行相应的解析和提取操作,同时也需要根据实际情况配置好数据库连接参数。