好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

利用python如何爬取js里面的内容

普通获取代码示例:
import requests
from bs4 import BeautifulSoup

res = requests.get('http://news.sina测试数据.cn/c/nd/2017-06-12/doc-ifyfzhac1650783.shtml')
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text,'html.parser')
#取评论数
commentCount = soup.select_one('#commentCount1')
print(commentCount.text) 

在消息头中我们可以看的该js文件的访问路径及请求方式

代码示例

import json
comments = requests.get('http://comment5.news.sina测试数据.cn/page/info?version=1&format=js&channel=gn&newsid=comos-fyfzhac1650783')
comments.encoding = 'utf-8'
print(comments)
jd = json.loads(comments.text.strip('var data=')) #移除改var data=将其变为json数据
print(jd['result']['count']['total']) 


注释:这里解释下为何需要移除 var data= 因为在获取时字符串前缀是包含var data=的 其不符合json数据格式 因此转化时需将其从请求内容中移除

取评论总数时为何使用jd[ 'result' ][ 'count' ][ 'total' ]


以上就是利用python如何爬取js里面的内容的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于利用python如何爬取js里面的内容的详细内容...

  阅读:51次