python爬取ajax請求,返回的json資料格式化報錯json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
阿新 • • 發佈:2018-11-08
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()