抓取博客園(https://www.cnblogs.com/)分類列表(下圖紅框所示),在瀏覽器直接查看網頁的源碼,是看不到這部份內容的.html
抓取方法以下:json
使用谷歌瀏覽器,按F12,切換到Network,點擊第一個按鈕開始抓包.瀏覽器
按F5從新刷新頁面,左邊會出現全部請求內容.cookie
這裏就須要一個一我的工查看,以下圖,找到所需內容.app
切換到Headers選項,能夠查看到請求的類型:post
方式:postui
"content-type":"application/json; charset=UTF-8", "user-agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Mobile Safari/537.36", "x-requested-with": "XMLHttpRequest", "accept":"text/plain, */*; q=0.01", "accept-encoding": "gzip, deflate, br",
最下面的Request Payload就是post的數據.url
from MyRequestPost import MyRequestPost#本身寫的一個公用類 from lxml import etree headers = { "content-type":"application/json; charset=UTF-8", "user-agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Mobile Safari/537.36", "x-requested-with": "XMLHttpRequest", "accept":"text/plain, */*; q=0.01", "accept-encoding": "gzip, deflate, br", "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7", #"cookie": "xxx" }; data = '{"cateIds": "108698,2,108701,108703,108704,108705,108709,108712,108724,4"}' post = MyRequestPost(url="https://www.cnblogs.com/aggsite/SubCategories",headers = headers,data = data.encode('utf-8')) print(post.htmlCode);
而後輸出結果以下:spa
這裏有個小坑:code
提交的數據看起來是json數據,開始我是這麼寫的:
data = {"cateIds": "108698,2,108701,108703,108704,108705,108709,108712,108724,4"},看起來名正言順的json呢,可是老是返回500錯誤:
後來直接把json字符串加了引號,終於成功.
另外:
"content-type"="application/json; charset=UTF-8"的時候,數據是json數據.
Content-Type=application/x-www-form-urlencoded; charset=UTF-8,數據應該是表單數據.
例如:
data = [
(‘user’, 'xxxx'),
('password', '5xxxx'),]