#--*--conding:utf-8 --*-- # Author: Gonggong # 使用python爬取一個網頁中表格的內容,並把抓取到的內容以json格式保存到文件中 import requests from lxml import etree import json # 獲取網頁源代碼 r = requests.get('http://ipwhois.cnnic.cn/bns/query/Query/ipwhoisQuery.do?queryOption=ipv4&txtquery=8.8.8.8') # 使用xpath對爬取的源代碼進行處理 dom_tree = etree.HTML(r.content) links = dom_tree.xpath("/html/body/center[1]/table[1]/tr/td/font") # 取出links的單行、雙行的數據 res1 = [i.text for i in links[::2]] res2 = [i.text for i in links[1::2]] # 把兩行數據組合成在一起 result = tuple(zip(res1, res2)) # 使用json格式保存到文件中 json.dump(result, open('/tmp/xpath_get.txt', 'w'), ensure_ascii=False)