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加密,同时也方便了我们爬取数据。