温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么用python写网络爬虫

发布时间:2021-04-25 14:32:45 来源:亿速云 阅读:114 作者:小新 栏目:开发技术

小编给大家分享一下怎么用python写网络爬虫,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

Python主要用来做什么

Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌入式应用开发;5、游戏开发;6、桌面应用开发。

新浪微博需要登录才能爬取,这里使用m.weibo.cn这个移动端网站即可实现简化操作,用这个访问可以直接得到的微博id。

分析新浪微博的评论获取方式得知,其采用动态加载。所以使用json模块解析json代码

单独编写了字符优化函数,解决微博评论中的嘈杂干扰字符

本函数是用python写网络爬虫的终极目的,所以采用函数化方式编写,方便后期优化和添加各种功能

# -*- coding:gbk -*-
import re
import requests
import json
from lxml import html
#测试微博4054483400791767
comments=[]

def get_page(weibo_id):
  url='https://m.weibo.cn/status/{}'.format(weibo_id)
  html=requests.get(url).text
  regcount=r'"comments_count": (.*?),'
  comments_count=re.findall(regcount,html)[-1]
  comments_count_number=int(comments_count)
  page=int(comments_count_number/10)
  return page-1

def opt_comment(comment):
  tree=html.fromstring(comment)
  strcom=tree.xpath('string(.)')
  reg1=r'回复@.*?:'
  reg2=r'回覆@.*?:'
  reg3=r'//@.*'
  newstr=''
  comment1=re.subn(reg1,newstr,strcom)[0]
  comment2=re.subn(reg2,newstr,comment1)[0]
  comment3=re.subn(reg3,newstr,comment2)[0]
  return comment3

def get_responses(id,page):
  url="https://m.weibo.cn/api/comments/show?id={}&page={}".format(id,page)
  response=requests.get(url)
  return response

def get_weibo_comments(response):
  json_response=json.loads(response.text)
  for i in range(0,len(json_response['data'])):
    comment=opt_comment(json_response['data'][i]['text'])
    comments.append(comment)


weibo_id=input("输入微博id,自动返回前5页评论:")
weibo_id=int(weibo_id)
print('\n')
page=get_page(weibo_id)
for page in range(1,page+1):
  response=get_responses(weibo_id,page)
  get_weibo_comments(response)

for com in comments:
  print(com)
print(len(comments))

以上是“怎么用python写网络爬虫”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI