PYTHON网络爬虫概述

在对人才网(前程无忧)进行非selenium分析时,找到源代码里面存在

<script type="text/javascript">
{此处省略一万字}</script>

这是通过JavaScript写了一个脚本文件
可是,这个怎么直接提取出来呢?

解决方法如下

'''
破解前程无忧js文件
'''
#导入模块
import requests
from bs4 import BeautifulSoup
import parsel
import json
from fake_useragent import UserAgent
url = 'https://search.51job.com/list/000000,000000,0000,00,9,99,%25E7%2588%25AC%25E8%2599%25AB%25E5%25B7%25A5%25E7%25A8%258B%25E5%25B8%2588,2,1.html?lang=c&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0&line=&welfare='
headers = {
'User-Agent':UserAgent().random
}
res = requests.get(url,headers=headers)
html = parsel.Selector(res.text)
#此处除了用BeautifulSoup方法外,也可以用xpath和re方法
soup = BeautifulSoup(res.text,'lxml')
body = soup.find_all('script', type='text/javascript')[2]
for x in body:
print(x)

输出结果

window.__SEARCH_RESULT__ = {'此处省略一万字'}

这个看起来是不是有些别扭?我们要的是后面的字典,前面这些字母怎么处理呢?

print(type(x))
#class 'bs4.element.NavigableString'>

从此处可以知道,这是一个字符串
好说了,直接提取后面的字典

print(x[29:])
#{"top_ads": [], "auction
print(type(x[29:]))
#class 'str'

此处显示的是一个字符串(str),可是这里不是字典吗?怎么回事?

仔细回想一下,对于这些脚本文件我们如果要通过正常的途径获取是要经过Ajax方法获取的,而Ajax方法是不是得到的是一个json数据?!

对的,这里也是,那么我们用json方法来转化成python格式

print(type(json.loads(x[29:])))
print(json.loads(x[29:]))
#结果如下
<class 'dict'>
{'此处省略一万字'}

完结