python爬取ajax请求,返回的json数据格式化报错json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

python爬取ajax请求,返回Json数据中带有<html><head></head><body><prestyle="word-wrap: break-word; white-space: pre-wrap;"></pre></body></html>标签解决方法

一、分析:

如何使返回的数据去除非json格式的数据,

二、使用replace()方法:

replace()方法语法:

str.replace(old, new[, max])
  • old -- 将被替换的子字符串。
  • new -- 新字符串,用于替换old子字符串。
  • max -- 可选字符串, 替换不超过 max 次

返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。

三、最终解决方式源码如下:

import json
from urllib.parse import urlencode

from selenium import webdriver

def get_page_index(offset, keyword):
    data = {
        'offset': offset,
        'format': 'json',
        'keyword': keyword,
        'autoload': 'true',
        'count': '20',
        'cur_tab': '1',
        'from': 'search_tab',
    }
    url = 'http://www.toutiao.com/search_content/?' + urlencode(data)
    browser = webdriver.PhantomJS()
    try:
        browser.get(url)
        return browser.page_source
    finally:
        browser.close()

def parse_page_index(html):
    '''解析网页资源'''
    data = json.loads(html)
    if data and 'data' in data.keys():
        '''寻找key为data的数据'''
        for item in data.get('data'):
            yield item.get('article_url')

def main():
    html = get_page_index(0, '街拍')
    '''加入如下两行代码即可'''
    html = html.replace('<html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">', '')
    html = html.replace('</pre></body></html>', '')
    # print(html)
    for url in parse_page_index(html):
        print(url)

if __name__ == '__main__':
    main()

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值