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()

猜你喜欢

转载自blog.csdn.net/beta_safe/article/details/80456438