先開(kāi)啟mitmproxy, 命令如下
mitmweb -s 抓取.py
我們需要對(duì)request的url做過(guò)濾,發(fā)現(xiàn)請(qǐng)求的url包含有ajax字符就提取response內(nèi)容,然后使用bs4解析xml,獲取需要的數(shù)據(jù),代碼如下:
from mitmproxy import ctx
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
# def request(flow):
#? ? flow.request.headers['user-agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
def run_selenium():
? ? driver = webdriver.PhantomJS()
? ? url = 'http://wsjs.saic.gov.cn/txnRead01.do?SVVVdE0o=KalIkqkedI6edI6edpSi_r6ZKYhRAJQahSFFMpYtTEaqqH0'
? ? driver.get(url)
def response(flow):
? ? ctx.log.error('獲取的url是: ' + flow.request.url)
? ? if 'txnRead02.ajax' in flow.request.url:
? ? ? ? soup = BeautifulSoup(flow.response.text, 'xml')
? ? ? ? for record in soup.find_all('record'):
? ? ? ? ? ? item = {}
? ? ? ? ? ? item['index'] = record.find('index').get_text()
? ? ? ? ? ? item['注冊(cè)號(hào)'] = record.find('sn').get_text()
? ? ? ? ? ? item['中文名稱(chēng)'] = record.find('hnc').get_text()
? ? ? ? ? ? item['注冊(cè)時(shí)間'] = record.find('mno').get_text()
? ? ? ? ? ? item['英文名稱(chēng)'] = record.find('hne').get_text()
? ? ? ? ? ? item['國(guó)際分類(lèi)'] = record.find('nc').get_text()
? ? ? ? ? ? ctx.log.warn(str(item))
? ? ? ? ? ? df = pd.DataFrame(item, index = ['0'])
? ? ? ? ? ? header = True if item['index'] == 1 else False
? ? ? ? ? ? df.to_csv('/爬蟲(chóng)例子/商標(biāo).csv', mode = 'a', encoding='utf_8_sig', index = False, header = header)
? ? ? ? # [ctx.log.warn(a.get('href')) for a in soup.find_all('a')]
if __name__ == "__main__":
? ? run_selenium()
在這里我并沒(méi)有使用selenium來(lái)自動(dòng)調(diào)用網(wǎng)頁(yè),后續(xù)會(huì)繼續(xù)對(duì)此進(jìn)行改進(jìn)的。
需要手動(dòng)進(jìn)行的操作就是翻頁(yè),翻頁(yè)后,mitmproxy會(huì)自動(dòng)獲取結(jié)果并且解析保存為csv的文件。