上周作业:爬取豆瓣TOP250电影信息
1 ''' 2 爬取豆瓣TOP250电影信息 3 4 主页: 5 第一页: 6 https://movie.douban.com/top250?start=0&filter= 7 第二页: 8 https://movie.douban.com/top250?start=25&filter= 9 第三页: 10 https://movie.douban.com/top250?start=50&filter= 11 第十页: 12 https://movie.douban.com/top250?start=225&filter= 13 GET 14 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36 15 16 re正则: 17 # 电影详情页url、图片链接、电影名称、电影评分、导演、主演、电影上映时间、评价人数、简介 18 <div class="item">.*?href="(.*?)">.*?src="(.*?)" class="">.*?<span class="title">(.*?)</span>.*?<div class="bd">.*?导演:(.*?)<br>(.*?)</p>.*?<span class="rating_num".*?>(.*?)</span>.*?<span>(.*?)人评价<span class="inq">(.*?)</span> 19 ''' 20 import requests 21 import re 22 23 24 headers = { 25 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36' 26 } 27 base_url = 'https://movie.douban.com/top250?start={}&filter=' 28 29 n = 0 30 for line in range(10): 31 print() 32 url = base_url.format(n) 33 print(type(n)) 34 n += 25 35 print(url) 36 # 1、往豆瓣TOP250发送请求获取响应数据 37 response = requests.get(url, headers=headers) 38 39 # print(response.text) 40 41 # 2、通过正则解析提取数据 42 # 电影详情页url、图片链接、电影名称、电影评分、评价人数 43 movie_content_list = re.findall( 44 # 正则规则 45 # 电影评分、评价人数、 46 47 '<div class="item">.*?href="(.*?)">.*?src="(.*?)" class="">.*?<span class="title">(.*?)</span>.*?<div class="bd">.*?导演:(.*?)<br>(.*?)</p>.*?<span class="rating_num".*?>(.*?)</span>.*?<span>(.*?)人评价.*?<span class="inq">(.*?)</span>', 48 49 # 解析文本 50 response.text, 51 52 # 匹配模式 53 re.S) 54 55 for movie_content in movie_content_list: 56 # 解压赋值每一部电影 57 detail_url, movie_jpg, name, daoyan, timer, point, num, desc = movie_content 58 data = f'电影名称:{name},详情页url:{detail_url}, 图片url:{movie_jpg},导演:{daoyan},上映时间:{timer}, 评分: {point}, 评价人数: {num}, 简介:{desc} ' 59 print(data) 60 61 # 3、保存数据,把电影信息写入文件中 62 with open('豆瓣top250.txt', 'a', encoding='utf-8') as f: 63 f.write(data)
今日内容:
1、requests之POST请求
2、requests高级用法
3、selenium基本使用
4、万能破解登录
一、requests之POST请求
1 ''' 2 post请求访问github 3 请求url: 4 https://github.com/session 5 请求方式: 6 POST 7 请求头: 8 # 上一次请求从哪里来 9 Referer:https://github.com/login 10 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36 11 请求体: 12 只有POST请求才会有请求体。 13 commit: 登入 14 utf8: ✓ 15 authenticity_token: 1ZoPGWJBCBMW/IzHozPRLB1UJBfw0/SnHtGeqbKULG1Xb1YPxFhKmKKFPs9meYV0IdjGKnXYqTH9nASzPNYOnw== 16 login: shendongnian 17 password: 1111 18 webauthn-support: supported 19 20 ''' 21 import requests 22 import re 23 24 # 一、访问login页面获取token信息 25 ''' 26 请求url: 27 https://github.com/login 28 请求方式: 29 GET 30 响应头: 31 Set-Cookie: 32 请求头: 33 Cookie: 34 User-Agent: 35 ''' 36 headers = { 37 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36' 38 } 39 40 response = requests.get(url='https://github.com/login', headers = headers) 41 # print(response.text) 42 # 把login页返回的cookies信息转换成字典 43 login_cookies = response.cookies.get_dict() 44 45 authenticity_token = re.findall('<input type="hidden" name="authenticity_token" value="(.*?)" />',response.text,re.S)[0] 46 47 print(authenticity_token) 48 49 # 二、往sessionurl发送POST请求 50 ''' 51 post请求登录github 52 请求url: 53 https://github.com/session 54 55 请求方式: 56 POST 57 58 请求头: 59 # 上一次请求从哪里来 60 Referer:https://github.com/login 61 Cookie:... 62 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36 63 64 请求体: 65 只有POST请求才会有请求体。 66 commit: 登入 67 utf8: ✓ 68 authenticity_token: 1ZoPGWJBCBMW/IzHozPRLB1UJBfw0/SnHtGeqbKULG1Xb1YPxFhKmKKFPs9meYV0IdjGKnXYqTH9nASzPNYOnw== 69 login: shendongnian 70 password: 1111 71 webauthn-support: supported 72 73 ''' 74 # 拼接头信息 75 headers2 = { 76 'Referer':'https://github.com/login', 77 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36' 78 } 79 80 81 # cookies = { 82 # 'Cookies':'' 83 # } 84 85 # 拼接请求体信息 86 from_data = { 87 "commit":"登入", 88 "utf8": "✓", 89 "authenticity_token":authenticity_token, 90 "login":"tankjam", 91 "password":"kermit46709394", 92 "webauthn-support":"unsupported" 93 } 94 95 # 往session地址发送post请求 96 # 携带请求头、请求体、login页的cookie信息 97 98 response2 = requests.post(url='https://github.com/session',data=from_data,headers = headers2,cookies=login_cookies) 99 print(response2.status_code) 100 # print(response2.text) 101 with open('github.html','w',encoding='utf-8') as f: 102 f.write(response2.text)
二、requests响应
1 ''' 2 post请求访问github 3 请求url: 4 https://github.com/session 5 请求方式: 6 POST 7 请求头: 8 # 上一次请求从哪里来 9 Referer:https://github.com/login 10 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36 11 请求体: 12 只有POST请求才会有请求体。 13 commit: 登入 14 utf8: ✓ 15 authenticity_token: 1ZoPGWJBCBMW/IzHozPRLB1UJBfw0/SnHtGeqbKULG1Xb1YPxFhKmKKFPs9meYV0IdjGKnXYqTH9nASzPNYOnw== 16 login: shendongnian 17 password: 1111 18 webauthn-support: supported 19 20 ''' 21 import requests 22 import re 23 24 # 一、访问login页面获取token信息 25 ''' 26 请求url: 27 https://github.com/login 28 请求方式: 29 GET 30 响应头: 31 Set-Cookie: 32 请求头: 33 Cookie: 34 User-Agent: 35 ''' 36 headers = { 37 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36' 38 } 39 40 response = requests.get(url='https://github.com/login', headers = headers) 41 # print(response.text) 42 # 把login页返回的cookies信息转换成字典 43 login_cookies = response.cookies.get_dict() 44 45 authenticity_token = re.findall('<input type="hidden" name="authenticity_token" value="(.*?)" />',response.text,re.S)[0] 46 47 print(authenticity_token) 48 49 # 二、往sessionurl发送POST请求 50 ''' 51 post请求登录github 52 请求url: 53 https://github.com/session 54 55 请求方式: 56 POST 57 58 请求头: 59 # 上一次请求从哪里来 60 Referer:https://github.com/login 61 Cookie:... 62 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36 63 64 请求体: 65 只有POST请求才会有请求体。 66 commit: 登入 67 utf8: ✓ 68 authenticity_token: 1ZoPGWJBCBMW/IzHozPRLB1UJBfw0/SnHtGeqbKULG1Xb1YPxFhKmKKFPs9meYV0IdjGKnXYqTH9nASzPNYOnw== 69 login: shendongnian 70 password: 1111 71 webauthn-support: supported 72 73 ''' 74 # 拼接头信息 75 headers2 = { 76 'Referer':'https://github.com/login', 77 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36' 78 } 79 80 81 # cookies = { 82 # 'Cookies':'' 83 # } 84 85 # 拼接请求体信息 86 from_data = { 87 "commit":"登入", 88 "utf8": "✓", 89 "authenticity_token":authenticity_token, 90 "login":"tankjam", 91 "password":"kermit46709394", 92 "webauthn-support":"unsupported" 93 } 94 95 # 往session地址发送post请求 96 # 携带请求头、请求体、login页的cookie信息 97 98 response2 = requests.post(url='https://github.com/session',data=from_data,headers = headers2,cookies=login_cookies) 99 print(response2.status_code) 100 # print(response2.text) 101 with open('github.html','w',encoding='utf-8') as f: 102 f.write(response2.text)
三、requests高级用法
1 import requests 2 3 https = http + ssl(携带证书) 4 5 6 #证书验证(大部分网站都是https) 7 import requests 8 # 如果是ssl请求,首先检查证书是否合法,不合法则报错,程序终端 9 response = requests.get('https://www.xiaohuar.com') 10 print(response.status_code) 11 12 # 改进1:去掉报错,但是会报警告 13 # import requests 14 # response = requests.get('https://www.xiaohuar.com', verify=False) # True携带证书 False不携带证书 15 # # 不验证证书,报警告,返回200 16 # print(response.status_code) 17 18 # 改进2:去掉报错,并且去掉警报信息 19 import requests 20 import urllib3 21 urllib3.disable_warnings() # 关闭警告 22 response = requests.get('https://www.xiaohuar.com', verify=False) 23 print(response.status_code) 24 25 # 改进3:加上证书 26 # 很多网站都是https,但是不用证书也可以访问,大多数情况都是可以携带也可以不携带证书 27 # 知乎百度等都是可带可不带 28 # 有硬性要求的,则必须带,比如对于定向的用户,拿到证书后才有权限访问某个特定网站 29 import requests 30 import urllib3 31 # urllib3.disable_warnings() # 关闭警告 32 # 伪代码 33 response = requests.get( 34 'https://www.xiaohuar.com', 35 # verify=False, 36 # /path/server.crt证书的存放目录,/path/key 37 cert=('/path/server.crt', '/path/key')) 38 print(response.status_code) 39 40 41 42 ''' 43 超时设置 44 ''' 45 46 超时设置 47 两种超时:float or tuple 48 timeout=0.1 # 代表接收数据的超时时间 49 timeout=(0.1,0.2) # 0.1代表链接超时 0.2代表接收数据的超时时间 50 51 import requests 52 53 response = requests.get('https://www.baidu.com', 54 timeout=0.0001) 55 56 print() 57 58 代理设置:先发送请求给代理,然后由代理帮忙发送(封ip是常见的事情) 59 import requests 60 proxies={ 61 # 带用户名密码的代理,@符号前是用户名与密码 62 'http':'http://tank:123@localhost:9527', 63 'http':'http://localhost:9527', 64 'https':'https://localhost:9527', 65 } 66 response=requests.get('https://www.12306.cn', 67 proxies=proxies) 68 69 print(response.status_code) 70 71 72 ''' 73 爬取西刺免费代理: 74 1.访问西刺免费代理页面 75 2.通过re模块解析并提取所有代理 76 3.通过ip测试网站对爬取的代理进行测试 77 4.若test_ip函数抛出异常代表代理作废,否则代理有效 78 5.利用有效的代理进行代理测试 79 80 <tr class="odd"> 81 <td class="country"><img src="//fs.xicidaili.com/images/flag/cn.png" alt="Cn"></td> 82 <td>112.85.131.99</td> 83 <td>9999</td> 84 <td> 85 <a href="/2019-05-09/jiangsu">江苏南通</a> 86 </td> 87 <td class="country">高匿</td> 88 <td>HTTPS</td> 89 <td class="country"> 90 <div title="0.144秒" class="bar"> 91 <div class="bar_inner fast" style="88%"> 92 93 </div> 94 </div> 95 </td> 96 <td class="country"> 97 <div title="0.028秒" class="bar"> 98 <div class="bar_inner fast" style="97%"> 99 100 </div> 101 </div> 102 </td> 103 104 <td>6天</td> 105 <td>19-05-16 11:20</td> 106 </tr> 107 re: 108 <tr class="odd">(.*?)</td>.*?<td>(.*?)</td> 109 110 ''' 111 import requests 112 import re 113 import time 114 115 HEADERS = { 116 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36', 117 } 118 119 120 def get_index(url): 121 time.sleep(1) 122 response = requests.get(url, headers=HEADERS) 123 return response 124 125 126 def parse_index(text): 127 ip_list = re.findall('<tr class="odd">.*?<td>(.*?)</td>.*?<td>(.*?)</td>', text, re.S) 128 for ip_port in ip_list: 129 ip = ':'.join(ip_port) 130 yield ip 131 132 def test_ip(ip): 133 print('测试ip: %s' % ip) 134 try: 135 proxies = { 136 'https': ip 137 } 138 139 # ip测试网站 140 ip_url = 'https://www.ipip.net/' 141 142 # 使用有效与无效的代理对ip测试站点进行访问,若返回的结果为200则代表当前测试ip正常 143 response = requests.get(ip_url, headers=HEADERS, proxies=proxies, timeout=1) 144 145 if response.status_code == 200: 146 print(f'有用的ip:{ip}') 147 return ip 148 149 # 若ip代理无效则抛出异常 150 except Exception as e: 151 print(e) 152 153 # 使用代理爬取nba 154 def spider_nba(good_ip): 155 url = 'https://china.nba.com/' 156 157 proxies = { 158 'https': good_ip 159 } 160 161 response = requests.get(url, headers=HEADERS, proxies=proxies) 162 print(response.status_code) 163 print(response.text) 164 165 166 if __name__ == '__main__': 167 base_url = 'https://www.xicidaili.com/nn/{}' 168 169 for line in range(1, 3677): 170 ip_url = base_url.format(line) 171 172 response = get_index(ip_url) 173 174 # 解析西刺代理获取每一个ip列表 175 ip_list = parse_index(response.text) 176 177 # 循环每一个ip 178 for ip in ip_list: 179 # print(ip) 180 181 # 对爬取下来的ip 进行测试 182 good_ip = test_ip(ip) 183 184 if good_ip: 185 # 真是代理,开始测试 186 spider_nba(good_ip) 187 188 189 # 认证设置 190 ''' 191 登录网站时,会弹出一个框,要求你输入用户名与密码(类似于alert),此时无法进入html页面,待授权通过后才能进入html页面。 192 193 Requests模块为我们提供了多种身份认证方式,包括基本身份认证等... 194 195 其原理指的是通过输入用户名与密码获取用户的凭证来识别用户,然后通过token对用户进行授权。 196 基本身份认证: 197 HTTP Basic Auth是HTTP1.0提出的认证方式。客户端对于每一个realm,通过提供用户名和密码来进行认证的方式当认证失败时,服务器收到客户端请求,返回401。 198 199 ''' 200 import requests 201 # 通过访问github的api来测试 202 url = 'https://api.github.com/user' 203 HEADERS = { 204 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36', 205 } 206 207 # 测试1,失败返回401 208 response = requests.get(url, headers=HEADERS) 209 print(response.status_code) # 401 210 print(response.text) 211 ''' 212 打印结果: 213 { 214 "message": "Requires authentication", 215 "documentation_url": "https://developer.github.com/v3/users/#get-the-authenticated-user" 216 } 217 ''' 218 219 # 测试2,通过requests.auth内的HTTPBasicAuth进行认证,认证成功返回用户信息 220 from requests.auth import HTTPBasicAuth 221 response = requests.get(url, headers=HEADERS, auth=HTTPBasicAuth('tankjam', 'kermit46709394')) 222 print(response.text) 223 224 225 # 测试3,通过requests.get请求内的auth参数默认就是HTTPBasicAuth,认证成功返回用户信息 226 # response = requests.get(url, headers=HEADERS, auth=('tankjam', 'kermit46709394')) 227 # print(response.text) 228 ''' 229 打印结果: 230 { 231 "login": "TankJam", 232 "id": 38001458, 233 "node_id": "MDQ6VXNlcjM4MDAxNDU4", 234 "avatar_url": "https://avatars2.githubusercontent.com/u/38001458?v=4", 235 "gravatar_id": "", 236 "url": "https://api.github.com/users/TankJam", 237 "html_url": "https://github.com/TankJam", 238 "followers_url": "https://api.github.com/users/TankJam/followers", 239 "following_url": "https://api.github.com/users/TankJam/following{/other_user}", 240 "gists_url": "https://api.github.com/users/TankJam/gists{/gist_id}", 241 "starred_url": "https://api.github.com/users/TankJam/starred{/owner}{/repo}", 242 "subscriptions_url": "https://api.github.com/users/TankJam/subscriptions", 243 "organizations_url": "https://api.github.com/users/TankJam/orgs", 244 "repos_url": "https://api.github.com/users/TankJam/repos", 245 "events_url": "https://api.github.com/users/TankJam/events{/privacy}", 246 "received_events_url": "https://api.github.com/users/TankJam/received_events", 247 "type": "User", 248 "site_admin": false, 249 "name": "kermit", 250 "company": null, 251 "blog": "", 252 "location": null, 253 "email": null, 254 "hireable": null, 255 "bio": null, 256 "public_repos": 6, 257 "public_gists": 0, 258 "followers": 0, 259 "following": 0, 260 "created_at": "2018-04-02T09:39:33Z", 261 "updated_at": "2019-05-14T07:47:20Z", 262 "private_gists": 0, 263 "total_private_repos": 1, 264 "owned_private_repos": 1, 265 "disk_usage": 8183, 266 "collaborators": 0, 267 "two_factor_authentication": false, 268 "plan": { 269 "name": "free", 270 "space": 976562499, 271 "collaborators": 0, 272 "private_repos": 10000 273 } 274 } 275 ''' 276 277 278 上传文件 279 import requests 280 281 # 上传文本文件 282 files1 = {'file': open('user.txt', 'rb')} 283 # files参数是POST请求固定参数 284 response = requests.post('http://httpbin.org/post', files=files1) 285 print(response.status_code) # 200 286 print(response.text) # 200 287 288 # 上传图片文件 289 files2 = {'jpg': open('一拳超人.jpg', 'rb')} 290 response = requests.post('http://httpbin.org/post', files=files2) 291 print(response.status_code) # 200 292 print(response.text) # 200 293 294 # 上传视频文件 295 files3 = {'movie': open('love_for_GD.mp4', 'rb')} 296 297 response = requests.post('http://httpbin.org/post', files=files3) 298 print(response.status_code) # 200 299 print(response.text) # 200
四、selenium基本使用
1 ''' 2 selenium模块讲解 3 一、什么是selenium? 4 最初是一个自动化测试工具。可以使用它帮我们驱动浏览器自动去执行某些自定义好的操作。例如在页面中执行JS代码、跳过登录验证。 5 (selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法执行javaScript代码的问题。 6 selenium可以驱动浏览器自动执行自定义好的逻辑代码,也就是可以通过代码完全模拟成人类使用浏览器自动访问目标站点并操作,那我们也可以拿它来做爬虫。 7 selenium本质上是通过驱动浏览器,完全模拟浏览器的操作,比如跳转、输入、点击、下拉等...进而拿到网页渲染之后的结果,可支持多种浏览器。) 8 9 二、为什么要使用selenium? 10 1、优点: 11 要使用requests模块登录需要分析大量的复杂通信流程,使用selenium可以轻松跳过登录验证。 12 2、缺点: 13 浏览器会加载css、js、图片、视频...数据,爬虫效率相比requests模块要低。 14 15 三、如何使用? 16 下载selenium模块: 17 pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple selenium 18 下载浏览器驱动: 19 http://npm.taobao.org/mirrors/chromedriver/2.38/ 20 ''' 21 22 # selenium之第一次测试 23 from selenium import webdriver # 用来驱动浏览器的 24 25 # 调用得到一个动作链对象,破解华东验证码的时候用的,可以拖动图片 26 from selenium.webdriver import ActionChains 27 28 # 按照什么方式查找属性,By.ID,By.CSS_SELECTOR,By.Class 29 from selenium.webdriver.common.by import By 30 31 from selenium.webdriver.common.keys import Keys # 键盘按键操作 32 33 # 和下面WebDriverWait一起用的,EC 是expected_conditions的别名 34 from selenium.webdriver.support import expected_conditions as EC 35 36 # 等待页面加载某些元素 37 from selenium.webdriver.support.wait import WebDriverWait 38 39 import time 40 41 # 通过谷歌浏览器驱动打开谷歌浏览器 42 # chrome = webdriver.Chrome(r'chromedriver.exe的绝对路径') 43 chrome = webdriver.Chrome(r'D:Pythonchromedriver_win32chromedriver') # 括号内输入chromedriver.exe的绝对路径 44 ''' 45 # chromedriver.exe存放于python解释器的Scripts文件夹中 46 47 # chrome是一个驱动对象 48 chrome = webdriver.Chrome() 49 ''' 50 ''' 51 实例1 52 ''' 53 54 # 若try出现异常 55 try: 56 # 往tank博客主页发送get请求 57 # chrome.get('https://www.cnblogs.com/kermitjam') 58 59 # 参数1:驱动对象 参数2:等待时间 60 wait = WebDriverWait(chrome, 10) 61 62 # 1、访问百度 63 chrome.get('https://www.baidu.com/') 64 65 # 2、查找input输入框 66 # 调用EC的presence_of_element_located() 67 input_tag = wait.until(EC.presence_of_element_located((By.ID, "kw"))) 68 # 此处可以写一个元组 69 # 参数1:查找属性的方式 70 # 参数2:属性的名字 71 72 # 3、搜索一拳超人 73 input_tag.send_keys('一拳超人') 74 75 # 4、按键盘回车键 76 input_tag.send_keys(Keys.ENTER) 77 78 time.sleep(3) 79 80 # 无论发生什么都会关闭浏览器 81 finally: 82 # 关闭浏览器 83 chrome.close() 84 85 86 87 ''' 88 实例2 89 ''' 90 try: 91 # 往tank博客主页发送get请求 92 # chrome.get('https://www.cnblogs.com/kermitjam') 93 94 # 参数1:驱动对象 参数2:等待时间 95 wait = WebDriverWait(chrome, 10) 96 97 # 1、访问百度 98 chrome.get('https://www.jd.com/') 99 100 # 2、查找input输入框 101 input_tag = wait.until(EC.presence_of_element_located((By.ID, "key"))) 102 103 # 3、搜索唐诗三百首 104 input_tag.send_keys('唐诗三百首') 105 106 # 4、根据class属性名称查找标签 107 search_button = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'button'))) 108 109 # 5、点击搜索按钮 110 search_button.click() 111 112 time.sleep(3) 113 114 # 无论发生什么都会关闭浏览器 115 finally: 116 # 关闭浏览器 117 chrome.close()
五、selenium之基本选择器
1 from selenium import webdriver 2 import time 3 4 5 ''' 6 隐式等待 7 ''' 8 # 获取驱动对象 9 driver = webdriver.Chrome(r'D:Pythonchromedriver_win32chromedriver') 10 11 # 获取 12 try: 13 # 显式等待:等待某个元素加载 14 # 参数1:驱动对象 参数2:等待时间 15 # wait = WebDriverWait(chrome, 10) 16 17 driver.get('https://china.nba.com') 18 19 # 隐式等待:等待页面所有元素加载 20 driver.implicitly_wait(10) 21 news_tag = driver.find_element_by_class_name('nav-news') 22 # 获取标签对象 23 print(news_tag) 24 # 获取标签名字 25 print(news_tag.ag_name) 26 time.sleep(10) 27 28 29 finally: 30 chrome.close() 31 32 33 34 ''' 35 ===============所有方法=================== 36 element是查找一个标签 37 elements是查找所有标签 38 39 1、find_element_by_link_text 通过链接文本去找 40 2、find_element_by_id 通过id去找 41 3、find_element_by_class_name 42 4、find_element_by_partial_link_text 43 5、find_element_by_name 44 6、find_element_by_css_selector 45 7、find_element_by_tag_name 46 ''' 47 try: 48 49 # 往百度主页发送请求 50 driver.get('https://www.baidu.com/') 51 driver.implicitly_wait(10) 52 53 # 1、find_element_by_link_text 通过链接文本去找 54 # 根据登录 55 send_tag = driver.find_element_by_link_text('登录') 56 send_tag.click() 57 58 59 # 2、find_element_by_partial_link_text 通过局部文本查找a标签 60 login_button = driver.find_element_by_partial_link_text('登') 61 login_button.click() 62 time.sleep(1) 63 64 # 3、find_element_by_class_name 根据class属性名查找 65 login_tag = driver.find_element_by_class_name('tang-pass-footerBarULogin') 66 login_tag.click() 67 time.sleep(1) 68 69 # 4、find_element_by_name 根据name属性查找 70 username = driver.find_element_by_name('userName') 71 username.send_keys('15055303102') 72 time.sleep(1) 73 74 75 # 5、find_element_by_id 通过id属性名查找 76 password = driver.find_element_by_id('TANGRAM__PSP_10__password') 77 password.send_keys('shenjin981002') 78 time.sleep(1) 79 80 # 6、find_element_by_css_selector 根据属性选择器查找 81 # 根据id查找登录按钮 82 login_submit = driver.find_element_by_css_selector('#TANGRAM__PSP_10__submit') 83 # login_submit = driver.find_element_by_css_selector('.pass-button-submit') 84 login_submit.click() 85 86 # 7、find_element_by_tag_name 根据标签名称查找标签 87 div = driver.find_element_by_tag_name('div') 88 print(div.tag_name) 89 90 time.sleep(10) 91 92 93 finally: 94 driver.close()
今日作业:
1、整理课堂笔记并编写博客
2、爬取快代理(参考爬取西刺代理代码)
https://www.kuaidaili.com/free/
3、熟悉selenium模块,敲上课例子
4、自动登录抽屉新热榜