鱼C论坛

 找回密码
 立即注册
查看: 2200|回复: 1

[作品展示] 微博评论内容爬取

[复制链接]
发表于 2023-9-7 12:08:33 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 underwood_yo 于 2023-9-8 17:33 编辑

同学需要爬取微博的评论内容以及时间,给了一个excel文件,包含需要爬取的网址:


                               
登录/注册后可看大图


  1. import numpy as np
  2. import pandas as pd
  3. from selenium import webdriver
  4. import re
  5. from selenium.webdriver.common.by import By
  6. from bs4 import BeautifulSoup
  7. import time

  8. chrome_options = webdriver.ChromeOptions()
  9. chrome_options.add_argument('--headless')
  10. browser = webdriver.Chrome(options=chrome_options)

  11. start_time = time.time()

  12. def crawer(url):
  13.     print('开始爬取'+ url)
  14.     browser.get(url)
  15.     time.sleep(1)
  16.     res = browser.page_source
  17.     return res

  18. def execution_data(res):
  19.     bs4_res = BeautifulSoup(res, 'html.parser')
  20.     text = bs4_res.select('#app > div.lite-page-wrap > div > div.main > div > article > div > div > div.weibo-text')[0].text
  21.     created_at = '"created_at": "(.*?)"'
  22.     time_ = re.findall(created_at, res,re.S)
  23.     return text,time_

  24. data = pd.read_excel('wangzhi.xlsx')

  25. text_all = []
  26. time_all = []
  27. for i in range(data.shape[0]-1):
  28.     try:
  29.         url = data['网址'].iloc[i]
  30.         res = crawer(url)
  31.         text = execution_data(res)[0]
  32.         time_ = execution_data(res)[1]
  33.         text_all.append(text)
  34.         time_all.append(time_)
  35.     except:
  36.         print('第'+ str(i+1) + '个网页出现问题')
  37.         print(url)
  38.         text = []
  39.         time_ = []
  40.         text_all.append(text)
  41.         time_all.append(time_)

  42. context = pd.DataFrame({'文本':text_all,'时间':time_all})
  43. context.to_excel('微博正文.xlsx')
  44. print('爬取完成')

  45. end_time = time.time()
  46. total_time = end_time - start_time
  47. print("所有任务结束,总耗时为:" + str(total_time))[postbg]bg8.png[/postbg]
复制代码

网址原数据

网址原数据

结果示意

结果示意
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

头像被屏蔽
发表于 2023-9-9 12:01:44 | 显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-22 17:45

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表