从零开始学Python——使用Selenium抓取动态网页数据
1.selenium抓取动态网页数据基础介绍
1.1 什么是AJAX
AJAX(Asynchronouse JavaScript And XML:异步JavaScript和XML)通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新,这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行局部更新。传统的网页(不使用Ajax)如果需要更新内容,必须重载整个网页页面。
因为传统的网页在传输数据格式方面,使用的是XML语法,因此叫做AJAX,其实现在数据交互基本上都是使用JSON。使用AJAX加载的数据,即使使用了JS将数据渲染到了浏览器中,在右键->查看网页源代码还是不能看到通过ajax加载的数据,只能看到使用这个url加载的html代码。
1.2 获取ajax数据的方式
法1:直接分析ajax调用的接口。然后通过代码请求这个接口。
法2:使用Selenium+chromedriver模拟浏览器行为获取数据。
方式 | 优点 | 缺点 |
分析接口 | 直接可以请求到数据。不需要做一些解析工作。代码量少,性能高。 | 分析接口比较复杂,特别是一些通过js混淆的接口,要有一定的js功底。容易被发现是爬虫。 |
selenium | 直接模拟浏览器的行为。浏览器能请求到的,使用selenium也能请求到。爬虫更稳定。 | 代码量多。性能低。 |
1.3 Selenium+chromedriver获取动态数据
Selenium相当于是一个机器人。可以模拟人类在浏览器上的一些行为,自动处理浏览器上的一些行为,比如点击,填充数据,删除cookie等。chromedriver是一个驱动Chrome浏览器的驱动程序,使用他才可以驱动浏览器。当然针对不同的浏览器有不同的driver。以下列出了不同浏览器及其对应的driver:
- Chrome:https://sites.google.com/a/chromium.org/chromedriver/downloads
- Firefox:https://github.com/mozilla/geckodriver/releases
- Edge:https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
- Safari:https://webkit.org/blog/6900/webdriver-support-in-safari-10/
1.4 安装Selenium和chromedriver
- 安装Selenium:Selenium有很多语言的版本,有java、ruby、python等。我们下载python版本的就可以了。
- pip install selenium
- 安装chromedriver:下载完成后,放到不需要权限的纯英文目录下就可以了。
1.5 快速入门
现在以一个简单的获取百度首页的例子来讲下Selenium和chromedriver如何快速入门:
from selenium import webdriver # chromedriver的绝对路径 driver_path = r'D:\ProgramApp\chromedriver\chromedriver.exe' # 初始化一个driver,并且指定chromedriver的路径 driver = webdriver.Chrome(executable_path=driver_path) # 请求网页 driver.get("https://www.baidu.com/") # 通过page_source获取网页源代码 print(driver.page_source)
1.6 selenium常用操作
参考:Selenium的使用
1.7 爬取拉钩网职位信息
直接直接分析ajax调用的接口爬取
import requests from lxml import etree import time import re headers = { "Accept":"application/json, text/javascript, */*; q=0.01", "Accept-Encoding":"gzip, deflate, br", "Accept-Language":"zh-CN,zh;q=0.9", "Connection":"keep-alive", "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36", "Referer":"https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=", "Origin":"https://www.lagou.com", "Host":"www.lagou.com", "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8", "Cookie":"_ga=GA1.2.1602115737.1553064534; user_trace_token=20190320144853-39b1375a-4adc-11e9-a253-525400f775ce; LGUID=20190320144853-39b13f88-4adc-11e9-a253-525400f775ce; WEBTJ-ID=20190408120043-169fb1afd63488-06179b118ca307-7a1437-2073600-169fb1afd648ed; _gid=GA1.2.1826141825.1554696044; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%22169fb1bb2c41ea-04951e55adc96a-7a1437-2073600-169fb1bb2c58d0%22%2C%22%24device_id%22%3A%22169fb1bb2c41ea-04951e55adc96a-7a1437-2073600-169fb1bb2c58d0%22%7D; sajssdk_2015_cross_new_user=1; _putrc=4C5D2603888320CA; JSESSIONID=ABAAABAAADEAAFIB00F5DDE71D51610901CB9E0031812BA; login=true; unick=%E4%BC%8D%E6%99%93%E4%B8%BD; showExpriedIndex=1; showExpriedCompanyHome=1; showExpriedMyPublish=1; hasDeliver=49; gate_login_token=7b04a40da89145a1fbc90a3d719616d28c8b0a303344ac37; index_location_city=%E6%88%90%E9%83%BD; X_MIDDLE_T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jYs0AdWgvuzUvYqn7tsg1Kxn7ts0Aw9UMNBuNqsUA78pyw15HKxn7tsg1nkrjm4nNts0ZK9I7qhUA7M5H00uAPGujYknjT1P1fkrjcY0ANYpyfqQHD0mgPsmvnqn0KdTA-8mvnqn0KkUymqn0KhmLNY5H00uMGC5H00uh7Y5H00XMK_Ignqn0K9uAu_myTqnfK_uhnqn0KEIjYs0AqzTZfqnanscznsc100mLFW5HRdPj0Y%26word%3D%25E6%258B%2589%25E5%258B%25BE%25E7%25BD%2591%26ck%3D1701.10.72.227.558.354.602.254%26shh%3Dwww.baidu.com%26sht%3D62095104_19_oem_dg%26us%3D1.0.1.0.1.301.0%26bc%3D110101; PRE_LAND=https%3A%2F%2Fwww.lagou.com%2Flp%2Fhtml%2Fcommon.html%3Futm_source%3Dm_cf_cpc_baidu_pc%26m_kw%3Dbaidu_cpc_cd_e110f9_d2162e_%25E6%258B%2589%25E5%258B%25BE%25E7%25BD%2591; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1553064535,1554696044,1554707975; TG-TRACK-CODE=index_search; SEARCH_ID=16b25888bc6f489f981996ef505d6930; X_HTTP_TOKEN=3704e5535eab672a10080745514b2c7fac0430c282; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1554708001; LGRID=20190408152002-b9743b5b-59ce-11e9-9a84-525400f775ce", "X-Anit-Forge-Code":"0" , "X-Anit-Forge-Token":'', "X-Requested-With":'XMLHttpRequest' } def get_detail_page_url(): datas =[] url = 'https://www.lagou.com/jobs/positionAjax.json' form_data = { "first":"faise", "pn":1, "kd":"python" } params = { 'city':'成都', 'needAddtionalResult':'false' } for pn in range(1,14): form_data['pn'] = pn response = requests.request(method='post',url=url,headers=headers,params = params,data = form_data) result = response.json() result_list = result['content']['positionResult']['result'] for position in result_list: position_id = position['positionId'] detail_url = 'https://www.lagou.com/jobs/%s.html'%position_id data = parse_detail_page(detail_url) datas.append(data) time.sleep(2) return datas def parse_detail_page(url): resonse = requests.request(method='get',url=url,headers = headers) text = resonse.text html = etree.fromstring(text,parser=etree.HTMLParser()) position_name = html.xpath('//span[@class="name"]/text()')[0].strip() detail_list = html.xpath('//dd[@class="job_request"]//span') salary = detail_list[0].xpath('text()')[0].strip() city = detail_list[1].xpath('text()')[0].strip() city = re.sub(r'[\s/]','',city) work_years = detail_list[2].xpath('text()')[0].strip() work_years = re.sub(r'[\s/]','',work_years) education = detail_list[3].xpath('text()')[0].strip() education = re.sub(r'[\s/]','',education) job_details = ''.join(html.xpath('//div[@class="job-detail"]//p//text()')) data = { "position_name":position_name, "salay":salary, "city":city, "work_years":work_years, "education":education, "job_details":job_details } return data def main(): datas = get_detail_page_url() print(datas) if __name__ == '__main__': main()
selenium结合lxml爬取
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from lxml import etree import re import time class Lagouspider(object): driver_path = r'E:\study\chromedriver\chromedriver.exe' def __init__(self): self.driver = webdriver.Chrome(executable_path=Lagouspider.driver_path) self.url = 'https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=' self.positions = [] def run(self): while True: self.driver.get(self.url) source = self.driver.page_source WebDriverWait(driver=self.driver,timeout=10).until(EC.presence_of_element_located((By.XPATH,'//div[@class="pager_container"]/span[last()]'))) self.parse_list_page(source) next_btn = self.driver.find_element_by_xpath('//div[@class="pager_container"]/span[last()]') if "pager_next_disabled" in next_btn.get_attribute('class'): break else: next_btn.click() time.sleep(1) def parse_list_page(self,source): html = etree.HTML(source) links = html.xpath('//a[@class="position_link"]/@href') for link in links: self.request_detail_page(link) time.sleep(1) def request_detail_page(self,url): self.driver.execute_script("window.open('%s')"%url) self.driver.switch_to.window(self.driver.window_handles[1]) WebDriverWait(self.driver,timeout=10).until(EC.presence_of_element_located((By.XPATH,'//span[@class="name"]'))) source = self.driver.page_source self.parse_detail_page(source) #关闭当前详情页 self.driver.close() #切换回职位列表页 self.driver.switch_to.window(self.driver.window_handles[0]) def parse_detail_page(self,source): html = etree.HTML(source) position_name = html.xpath('//span[@class="name"]/text()')[0].strip() detail_list = html.xpath('//dd[@class="job_request"]//span') salary = detail_list[0].xpath('text()')[0].strip() city = detail_list[1].xpath('text()')[0].strip() city = re.sub(r'[\s/]', '', city) work_years = detail_list[2].xpath('text()')[0].strip() work_years = re.sub(r'[\s/]', '', work_years) education = detail_list[3].xpath('text()')[0].strip() education = re.sub(r'[\s/]', '', education) desc = ''.join(html.xpath('//dd[@class="job_bt"]//text()')).strip() data = { "name": position_name, "salay": salary, "city": city, "work_years": work_years, "education": education, "desc": desc } print(data) print('+'*40) self.positions.append(data) if __name__ == '__main__': spider = Lagouspider() spider.run()
希望本文对你有所帮助~~如果对软件测试、接口测试、自动化测试、面试经验交流感兴趣可以私聊我或关注公众号“特斯汀软件测试”。免费领取最新软件测试大厂面试资料和Python自动化、接口、框架搭建学习资料!技术大牛解惑答疑,同行一起交流。
版权声明:
作者: freeclashnode
链接: https://www.freeclashnode.com/news/article-1190.htm
来源: FreeClashNode
文章版权归作者所有,未经允许请勿转载。
热门文章
- 9月1日|21M/S,Shadowrocket/SSR/V2ray/Clash免费节点订阅链接每天更新
- 9月15日|20.4M/S,Shadowrocket/V2ray/SSR/Clash免费节点订阅链接每天更新
- 8月31日|20.3M/S,V2ray/Shadowrocket/SSR/Clash免费节点订阅链接每天更新
- 8月30日|22.8M/S,SSR/Clash/Shadowrocket/V2ray免费节点订阅链接每天更新
- 8月29日|22.2M/S,V2ray/Clash/SSR/Shadowrocket免费节点订阅链接每天更新
- 8月24日|19.3M/S,Shadowrocket/V2ray/Clash/SSR免费节点订阅链接每天更新
- 9月2日|21.4M/S,SSR/Shadowrocket/Clash/V2ray免费节点订阅链接每天更新
- 8月28日|20.4M/S,SSR/Clash/Shadowrocket/V2ray免费节点订阅链接每天更新
- 8月27日|21.5M/S,Clash/V2ray/SSR/Shadowrocket免费节点订阅链接每天更新
- 9月16日|18M/S,SSR/Shadowrocket/Clash/V2ray免费节点订阅链接每天更新
最新文章
- 9月20日|19.4M/S,V2ray/SSR/Shadowrocket/Clash免费节点订阅链接每天更新
- 9月19日|23M/S,Clash/SSR/Shadowrocket/V2ray免费节点订阅链接每天更新
- 9月18日|22.9M/S,Clash/Shadowrocket/V2ray/SSR免费节点订阅链接每天更新
- 9月17日|21.6M/S,SSR/Shadowrocket/V2ray/Clash免费节点订阅链接每天更新
- 9月16日|18M/S,SSR/Shadowrocket/Clash/V2ray免费节点订阅链接每天更新
- 9月15日|20.4M/S,Shadowrocket/V2ray/SSR/Clash免费节点订阅链接每天更新
- 9月14日|20M/S,Shadowrocket/SSR/Clash/V2ray免费节点订阅链接每天更新
- 9月13日|22.3M/S,Shadowrocket/V2ray/Clash/SSR免费节点订阅链接每天更新
- 9月12日|22.9M/S,Clash/V2ray/Shadowrocket/SSR免费节点订阅链接每天更新
- 9月11日|20.4M/S,Shadowrocket/Clash/SSR/V2ray免费节点订阅链接每天更新