這個(gè)帖子之前我就在52破解論壇已經(jīng)發(fā)過了,最近發(fā)現(xiàn)簡書用來記錄學(xué)習(xí)過程中寫的一些代碼也蠻好用的症昏,特別是支持markdown語法哈哈哈哈笛钝。
之前呢,學(xué)習(xí)了爬蟲的一點(diǎn)點(diǎn)知識(shí)想實(shí)踐一下横堡,就想到了爬取易班的活躍度排名。(http://www.yiban.cn/yforumprovince/schoolrank/puid/15083998/type/2)
直接爬取會(huì)亂碼冠桃,問度娘得知是js代碼
借鑒了一點(diǎn)csdn前人代碼那就是用execjs跑js代碼
解決方法:
- 第一次嘗試返回521狀態(tài)碼命贴,查詢返回的response的信息,
- 將別人寫的pytho的execjs跑js代碼整合到自己代碼中,獲取cookies添加到頭部胸蛛,再次訪問就成功了污茵。
'''
Data:2020/3/12
--- 大威鍋丨DaWeiGuo ---
'''
import re
import requests
import execjs
import bs4
from bs4 import BeautifulSoup
import os
#修改頭部
base_headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.8",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4094.1 Safari/537..*",
}
#獲取返回信息
def page_html(url):
response = requests.get(url=url, headers=base_headers)
return response
#根據(jù)返回狀態(tài)碼執(zhí)行應(yīng)該進(jìn)行相應(yīng)的處理(200是成功的)
def parse(response):
if response.status_code == 521:
parse_js(response)
response = page_html(response.url)
parse_html(response)
elif response.status_code == 200:
parse_html(response)
#由于該網(wǎng)站返回的是js代碼所以用execjs庫來跑返回的js代碼
def parse_js(response):
# 獲取js數(shù)據(jù)
jsstr = re.search('(function.*)</script>', response.text).group(1)
# 修改js數(shù)據(jù),將數(shù)據(jù)作為返回
jsstr = jsstr.replace('eval("qo=eval;qo(po);")', "return po")
# 獲取方法與參數(shù)
func, para = re.search('setTimeout\(\"(.*?)\((.*?)\)",', response.text).group(1, 2)
# 解析js
parsejs = execjs.compile(jsstr).call(func, para)
# 獲取cookie
cookie = re.search("cookie=\\'(.*?);", parsejs).group(1)
# 添加cookie到headers
base_headers["Cookie"] = cookie
def parse_html(response):
list_1=[]
sum=0
soup=BeautifulSoup(response.text,"html.parser")
soup_main = soup.main
soup_main_a = soup_main.find_all(class_="name")
for a in soup_main_a:
sum=sum+1
list_1.append([a.string,sum])
printlist(list_1,sum)
def printlist(list_1,sum):
root='C:/Users/l1768/Desktop/'
path=root+'內(nèi)容.txt'
tplt='{0:{2}<10}\t{1:>10}'
print(tplt.format("學(xué)校名稱:","排名:",chr(12288)))
# if not os.path.exists(root):
# os.mkdir(path)
# f=open(path,'wb')
for i in range(sum):
a=('{0:' '<20}\t{1:' '^10}'.format(list_1[i][0],list_1[i][1]))
# f.write(a.encode('utf-8'))
# f.write('\n'.encode('utf-8'))
print(a)
# f.close()
# print("文件保存成功")
if __name__ == '__main__':
response = page_html("https://www.yiban.cn/yforumprovince/schoolrank/puid/15083998/type/2")
parse(response)
易班.png