能否不使用Selenium完成这个爬虫的功能
时间: 2024-03-26 16:37:20 浏览: 127
可以的,在这个任务中,我们主要需要获取页面中的微博内容和转发内容,可以使用 Python 的 requests 库和 BeautifulSoup 库来实现。具体实现步骤如下:
使用 requests 库发送 GET 请求,获取页面的 HTML 内容。
使用 BeautifulSoup 库解析 HTML 内容,提取微博内容和转发内容。
将微博内容和转发内容存入 MySQL 数据库中。
下面是一个基于 requests 和 BeautifulSoup 实现微博爬虫的示例代码:
import requests
from bs4 import BeautifulSoup
import pymysql
import datetime
# 构造请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
# 请求页面
url = 'https://weibo.com/n/%E4%B8%AD%E5%9B%BD%E9%A3%9F%E5%93%81%E5%8D%AB%E7%94%9F?from=feed&loc=at&nick=%E4%B8%AD%E5%9B%BD%E9%A3%9F%E5%93%81%E5%8D%AB%E7%94%9F&order=hot'
response = requests.get(url, headers=headers)
# 解析页面
soup = BeautifulSoup(response.text, 'html.parser')
# 获取微博内容
weibo_content = soup.select('.WB_feed_detail .WB_text.W_f14')[0].text
# 获取转发内容
repost_items = soup.select('.list_ul .list_li')
reposts = []
for item in repost_items:
nickname = item.select('.WB_text.W_f14')[0].text
content = item.select('.WB_text.W_f14 + .comment_txt')[0].text
reposts.append({'nickname': nickname, 'content': content})
# 将微博内容和转发内容存入 MySQL 数据库中
db = pymysql.connect(host='hostname', port=port, user='root', password='root', db='weibo', charset='utf8mb4')
cursor = db.cursor()
# 存储微博内容
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
sql = "INSERT INTO weibo_user (content, create_time) VALUES ('%s', '%s')" % (weibo_content, now)
cursor.execute(sql)
db.commit()
# 存储转发内容
weibo_id = cursor.lastrowid
for repost in reposts:
sql = "INSERT INTO weibo_repost (weibo_id, nickname, content) VALUES (%d, '%s', '%s')" % (weibo_id, repost['nickname'], repost['content'])
cursor.execute(sql)
db.commit()
db.close()
需要注意的是,如果页面中的内容需要登录才能查看,则需要先进行登录操作。另外,在爬虫过程中,需要注意不要过于频繁地请求同一个网站,以免被网站封禁 IP。
相关推荐
















