Python爬虫项目实战--模拟手机登录微博爬取博文转发评论点赞数据

Python爬虫实战项目

----爬取博文转评赞数据
import bs4     # 网页解析,获得数据
import re      # 正则表达式,进行文字匹配
import urllib.request,urllib.error    # 指定URL,获取网页数据
import xlwt    # 进行excel操作
from bs4 import BeautifulSoup
import json    # 导入json包
weibo_url = 'https://m.weibo.cn/status/JgOpIfygE?type=like&jumpfrom=weibocom#_rnd1598349641094'
def askURL(url):
    head = {  # 模拟浏览器头部信息
        'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
    }
    request = urllib.request.Request(url, headers=head)
    html = ''
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode('utf-8')
    except urllib.error.URLError as e:
        if hasattr(e, 'code'):
            print(e.code)
        if hasattr(e, 'reason'):
            print(e.reason)
    return html
html = askURL(weibo_url)
soup = BeautifulSoup(html, 'html.parser')
item = soup.find_all('script')
item = str(item)
findrepost = re.compile(r'"reposts_count": (.*?),')
findcom = re.compile(r'"comments_count": (.*?),')
findatt = re.compile(r'"attitudes_count": (.*?),')
repo = re.findall(findrepost,item)
com = re.findall(findcom,item)
att = re.findall(findatt,item)
print(repo)
print(com)
print(att)

  运行程序后,即可获得博文:
在这里插入图片描述
  的转评赞数据。
在这里插入图片描述
  模拟手机登录的重点在于,在设置headers请求头中的user-agent值时,设置为‘Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1’。即告诉服务器,我们是手机浏览器,我们只能接受类似于Safari能接受的文件。因此,微博发送回来的数据,并没有用JS加密,同时也方便了我们爬取数据。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值