搜索文档树,bs4其它用法,css选择器,selenium的使用

一免费代理池搭建

1.代理池分类

  • 代理有免费和收费代理
  • 代理有http代理和https代理
  • 匿名度
    -高匿:隐藏访问者ip
    -透明:服务端能拿到访问者ip

2.作为后端,如何拿到使用代理人的ip

  • 请求头中:x-forword-for
  • 如果一个 HTTP 请求到达服务器之前,经过了三个代理 Proxy1、Proxy2、Proxy3,IP 分别为 IP1、IP2、IP3,用户真实 IP 为 IP0,那么按照 XFF 标准,服务端最终会收到以下信息:
  • X-Forwarded-For: IP0, IP1, IP2
  • 如果拿IP3,remote-addr中

3.搭建免费代理池:

  • 使用python---》爬取免费的代理---》解析出ip和端口,地区---》存到库中
  • 使用flask---》搭建了一个web服务--》只要向 /get 发送一个请求,他就随机返回一个代理ip
  • 总结步骤:
1 把项目下载下来,pycharm打开https://github.com/jhao104/proxy_pool
2 安装依赖,虚拟环境
3 修改配置文件
	DB_CONN = 'redis://127.0.0.1:6379/2'
4 启动爬虫:python proxyPool.py schedule
5 启动web服务:python proxyPool.py server
6 以后访问:http://127.0.0.1:5010/get/

7 使用代码
import requests
res=requests.get('http://192.168.1.252:5010/get/?type=http').json()
print(res['proxy'])

二代理池使用

# 使用django写个项目---》只要一访问,就返回访问者ip

# 编写步骤
1 编写django项目,写一个视图函数
def index(request):
    ip=request.META.get('REMOTE_ADDR')
    return HttpResponse('您的ip 是:%s'%ip)

2 配置路由:
    from app01.views import index
    urlpatterns = [
        path('', index),
    ]
3 删除settings.py 中的数据库配置

4 把代码上传到服务端,运行djagno项目
python3.8 manage.py runserver 0.0.0.0:8080

5 本地测试:
import requests
res=requests.get('http://127.0.0.1:5010/get/?type=http').json()
print(res['proxy'])
res1=requests.get('http://47.113.229.151:8080/',proxies={'http':res['proxy']})
print(res1.text)

三爬取某视频网站

import requests
import re

res = requests.get('https://www.pearvideo.com/category_loading.jsp?reqType=5&categoryId=1&start=0')
# print(res.text)
# 解析出所有视频地址---》re解析
video_list = re.findall('<a href="(.*?)" class="vervideo-lilink actplay">', res.text)
# print(video_list)
for video in video_list:
    real_url = 'https://www.pearvideo.com/' + video
    video_id = video.split('_')[-1]
    # print('视频详情地址是:', real_url)
    # 向能返回mp4地址的接口发送请求:https://www.pearvideo.com/videoStatus.jsp?contId=1706684&mrd=0.05520583472057039
    # 直接发送请求,返现返回的结果中,没有mp4地址,但是在它的页面中就有
    # 必须携带referer,referer是视频详情地址
    # contId  是视频id号
    header={
        'Referer':real_url
    }
    res = requests.get('https://www.pearvideo.com/videoStatus.jsp?contId=%s&mrd=0.05520583472057039'%video_id,headers=header)
    # print(res.json())
    real_mp4_url=res.json()['videoInfo']['videos']['srcUrl']
    # print(real_mp4_url) # 视频不能播放
    mp4 = real_mp4_url.replace(real_mp4_url.split('/')[-1].split('-')[0], 'cont-%s' % video_id)
    print('能播放的视频地址:',mp4)

    # 把视频下载到本地
    res=requests.get(mp4)
    with open('./video/%s.mp4'%video_id,'wb') as f:
        for line in res.iter_content():
            f.write(line)
      
 '''
 注意:
 1 发送ajax请求,获取真正视频地址
 2 发送ajax请求时,必须携带referer
 3 返回的视频地址,需要处理后才能播放
 '''

四 爬取新闻

# 解析库:汽车之家
# bs4 解析库  pip3 install beautifulsoup4

import requests
from bs4 import BeautifulSoup

res = requests.get('https://www.autohome.com.cn/news/1/#liststart')
# print(res.text)
# 第一个参数,是要总的字符串
# 第二个参数,使用哪个解析库 :html.parser:内置的,不需要额外安装,速度慢一些      lxml:额外安装lxml  pip3 install lxml
soup = BeautifulSoup(res.text, 'html.parser')
# 查找  标签
# 1 找到所有 类名是article 的ul标签
ul_list = soup.find_all(name='ul', class_='article')
# print(len(ul_list))

# 2 循环每个ul---》找出每个ul内部的所有li
for ul in ul_list:
    li_list = ul.find_all(name='li')
    # print(li_list)
    for li in li_list:  # 查找每个li标签中得
        h3 = li.find(name='h3')
        if h3:
            # 拿出h3标签的文本内容
            title = h3.text
            content=li.find('p').text # 第一个参数就是name
            # 标签对象 .attrs 拿到标签的所有属性,只要属性中得href
            url='https:'+li.find(name='a').attrs['href']
            # 可以不用 .attrs  直接取属性也可以
            img=li.find('img')['src']
            print('''
            文章标题:%s
            文章摘要:%s
            文章url:%s
            文章图片:%s
            ''' % (title,content,url,img))

            # 1 所有图片下载到本地
            # 2 在mysql中创建一个表 article---》id,title,content,url,img--->把爬回来的数据,存到数据库--》pymysql


五搜索文档树

    from bs4 import BeautifulSoup

    html_doc = """
    <html><head><title>The Dormouse's story</title></head>
    <body>
    <p class="title"><b>The Dormouse's story</b><span>lqz</span></p>

    <p class="story">Once upon a time there were three little sisters; and their names were
    <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
    <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
    <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
    and they lived at the bottom of a well.</p>

    <p class="story">...</p>
    """

    soup = BeautifulSoup(html_doc,'html_parser')

五种过滤器:字符串、正则表达式、列表、True、方法

  • find_all :找所有符合的标签 放入列表中
  • find 找一个

1.1 字符串---无论按标签名,属性,文本内容都是按字符串形式查找

  # p = soup.find(name='p')
  # p = soup.find('p') #  找到第一个p标签  <p class="title"><b>The Dormouse's story</b><span>lqz</span></p>

  # 找到类名为story的p标签,class 在python中是个关键字,因此后面要加_
  # p = soup.find(name='p', class_='story')

  # 可以按标签名,可以按属性,还可以按文本内容
  # 按文本内容
  # obj = soup.find(name='span', text='lqz') # text已经被弃用,用string代替
  # obj = soup.find(name='span', string='lqz')

  # 按属性
  # obj = soup.find(name='a', id='link3')
  # obj = soup.find(href="http://example.com/tillie")
  # 属性还可以写成这样
  # obj = soup.find(attrs={'href': 'http://example.com/tillie'})
  # print(obj)

1.2 正则表达式---无论按标签名,属性,文本内容都是按正则形式查找

  # 按名字
  # 找到所有名字以b开头的所有标签
  import re

  # obj = soup.find_all(name=re.compile('^b'))

  # 找到以y结尾的所有标签
  # obj = soup.find_all(name=re.compile('y$'))

  # 按属性
  # obj = soup.find_all(href=re.compile('^http:'))

  # 按文本
  # obj = soup.find_all(string=re.compile('lqz'))

1.3 列表---无论按标签名,属性,文本内容都是按列表形式查找

  # obj = soup.find_all(name=['p','a'])
  # obj = soup.find_all(class_=['sister', 'title'])

1.4 True---无论按标签名,属性,文本内容都是按布尔形式查找

# obj = soup.find_all(id=True)
# obj = soup.find_all(href=True)
# obj = soup.find_all(name='img',src=True)
# print(obj)

1.5方法---无论按标签名,属性,文本内容都是按方法形式查找

def has_class_but_no_id(tag):
  return tag.has_attr('class') and not tag.has_attr('id')

print(soup.find_all(name=has_class_but_no_id))  # 有class 属性没有id属性

爬取图片

    import requests
    from bs4 import BeautifulSoup

    res = requests.get('https://www.duitang.com/album/?id=102467089')
    # print(res.text)
    soup = BeautifulSoup(res.text, 'html.parser')
    ul = soup.find('ul', class_='clearfix')
    img_list = soup.find_all(name='img', src=True)
    for img in img_list:
        try:
            url = img.attrs.get('src')
            if not url.startswith('http'):
                url = 'https://c-ssl.dtstatic.com' + url
            print(url)
            res1 = requests.get(url)
            name = url.split('/')[-1]
            with open('./img/%s' % name, 'wb') as f:
                for line in res1.iter_content():
                    f.write(line)
        except Exception as e:
            continue

六bs4其它用法

1 遍历,搜索文档树--->bs4还可以修改xml

	-java的配置文件一般喜欢用xml写
    -.conf
    -.ini
    -.yaml
    -.xml
from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" id='id_xx' xx='zz'>lqz <b>The Dormouse's story <span>彭于晏</span></b>  xx</p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""
# soup=BeautifulSoup(html_doc,'html.parser')
soup = BeautifulSoup(html_doc,'lxml')

# 1 文档容错能力
# res = soup.prettify()
# print(res)

# 2 遍历文档树: 文档树:html开头 ------html结尾,中间包含了很多标签
# 通过.查找标签
# print(soup.html.head.title)

# 3 通过 . 找到p标签  只能找到最先找到的第一个
# print(soup.html.body.p)
# print(soup.p)

# 4.获取标签的名称
# p = soup.html.body.p
# print(p.name)

# 5 获取标签的属性
# p = soup.html.body.p
# # print(p.attrs.get('class')) # class 特殊,可能有多个,所以放在列表汇总
# # print(soup.a.attrs.get('href'))
# print(soup.a['href'])

# 6 获取标签的文本内容
# 6.1  标签对象.text  # 拿标签子子孙孙
# 6.2  标签对象.string # 该标签有且只有自己有文本内容才能拿出来
# 6.3  标签对象.strings # 拿子子孙孙,都放在生成器中
# print(soup.b.text)
# print(soup.p.text)
# print(soup.html.body.p.string) # 不能有子 孙
# print(soup.html.body.p.b.string) # 有且只有它自己

# print(soup.html.body.p.strings) # generator 生成器---》把子子孙孙的文本内容都放在生成器中,跟text很像
# print(list(soup.html.body.p.strings)) # generator 生成器---》把子子孙孙的文本内容都放在生成器中,跟text很像

# 8 子节点、子孙节点
# print(soup.p.contents) # p下所有子节点,只拿直接子节点

# print(soup.p.children) # 直接子节点 得到一个迭代器,包含p下所有子节点
# for i,child in enumerate(soup.p.children):
#     print(i, child)

# print(soup.p.descendants) #获取子孙节点,p下所有的标签都会选择出来  generator
# for i,child in enumerate(soup.p.descendants):
#     print(i,child)

#9、父节点、祖先节点
# print(soup.a.parent) #获取a标签的父节点
# print(list(soup.a.parents))  #找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...

#10、兄弟节点
# print(soup.a.next_sibling) # 下一个兄弟
# print(soup.a.previous_sibling) #上一个兄弟

# print(list(soup.a.next_siblings)) #下面的兄弟们=>生成器对象
print(soup.a.previous_siblings) #上面的兄弟们=>生成器对象

2 find_all 其他参数

    -limit=数字   找几条 ,如果写1 ,就是一条

    -recursive  默认是true
    obj = soup.html.body.find_all(name='a', recursive=False)

3 搜索文档树和遍历文档树可以混用,找属性,找文本跟之前学的一样

七 css选择器

css选择器:https://www.runoob.com/cssref/css-selectors.html

  import requests
  from bs4 import BeautifulSoup
  res = requests.get('https://www.cnblogs.com/liuqingzheng/p/16005896.html')
  # print(res.text)

  # 方式一:
  soup=BeautifulSoup(res.text,'html.parser')
  # a=soup.find(name='a',title='下载哔哩哔哩视频')
  # print(a.attrs.get('href'))

  # 方式二:按照css生成器找到名字为下载哔哩哔哩视频的链接
  # p=soup.select('#cnblogs_post_body p:nth-child(2) a:nth-child(5)')[0].attrs.get('href')[0].attrs.get('href')

  # 方式三:直接copy selector
  a=soup.select('#cnblogs_post_body > p:nth-child(2) > a:nth-child(5)')[0].attrs.get('href')
  print(a)

八案例

1.数据存到mysql中

import requests
from bs4 import BeautifulSoup
import pymysql

conn = pymysql.connect(
    user='root',
    password="1234",
    host='127.0.0.1',
    database='cnblogs',
    port=3306,
)
cursor = conn.cursor()


res = requests.get('https://www.autohome.com.cn/news/1/#liststart')
soup = BeautifulSoup(res.text, 'html.parser')
ul_list = soup.find_all(name='ul', class_='article')
for ul in ul_list:
    li_list = ul.find_all(name='li')
    for li in li_list:
        h3 = li.find(name='h3')
        if h3:
            title = h3.text
            content = li.find('p').text
            url = 'https:' + li.find(name='a').attrs['href']
            img = li.find('img')['src']
            print('''
            文章标题:%s
            文章摘要:%s
            文章url:%s
            文章图片:%s
            ''' % (title, content, url, img))

            # 1 所有图片下载到本地
            # 2 在mysql中创建一个表 article---》id,title,content,url,img--->把爬回来的数据,存到数据库--》pymysql
            cursor.execute("INSERT INTO news (title,content,img,url) VALUES (%s,%s,%s,%s)",args=[title,content,img,url])
            conn.commit()

结果:

2.上传图片

import requests
from bs4 import BeautifulSoup

res = requests.get('https://pic.netbian.com/tupian/32518.html')
# 默认为utf-8格式,如果为其他格式,就需要更改
res.encoding = 'gbk'
# print(res.text)
soup = BeautifulSoup(res.text,'html.parser')
ul = soup.find('ul',class_='clearfix')
img_list = ul.find_all(name='img',src=True)
for img in img_list:
    try:
        url = img.attrs.get('src')
        if not url.startswith('http'):
            url = 'https://pic.netbian.com' + url
        res1 = requests.get(url)
        name = url.split('-')[-1]
        with open('./img/%s' % name, 'wb') as f:
            for line in res1.iter_content():
                f.write(line)
    except Exception as e:
        continue

结果:

3.上传cnblogs图片

import requests

header = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0',
'Referer':'https://i.cnblogs.com/',
'Cookie':
'_ga=GA1.1.106786264.1698637502; _ga_1C8GHT1MXM=GS1.1.1702906929.2.0.1702906929.0.0.0; .Cnblogs.AspNetCore.Cookies=CfDJ8DZoAyJmInJHoSwqM1IbzdRsNIUfsGFHLG7Txw1-PzuBk0_VWowg0EKcWEFV0y4Hm5UTyf9EnRGKRGIdUtoQOxw-p9Wjv-afg64G374oSdPZsiK_3ERjEATk4JbT0I-9zZ71HXtEqN4GgkZvjUt4dhCz2Fpf0xbIhUGAD0_gUCXZziah9rcfqvN8Aa2vYJL8cZVrboF2xE68Jlq06wp8IMhl-NzA-jfEhn5e6CXq2VABgAYVlQlCeu6Rw_c32Hd2pc1I7NT5lPCSTgnsGwR4WhD3CUtRDdeV53KhuJdfeUGqV1X7ohy33vTPJ3ACM16ibvC7ncJawasK8EHkGGQhlzdI1JOobGd1ukVQIF6u8MEbxA_CQ7M1bs4k_DRiNhojWJqCEf9FTKOkWumGmocS5tPMgPiQW-xVWRO0xrdV6pQSAli7BUmnSWReRXUcn5xejFiQapKdbYIjUn0tUpLL9K50j9Vj3LsV6w2E2GxGZNgrI0O86Dba0d1KrqjuBRzzRSbAohYDb3AMi3m0wSPvAnyov2NGfrm8oEX3jhFRaUV1-MXLmDr7bhNS1Gn0-CpguFoGbiEPBZF_IdW_SeyC2gxkdRVPRZe0BoTZwtjogbRU; .CNBlogsCookie=43B8F58F13C28FE89AD83B74B377CACAAFBA43BC7072AA2CE817CA067BF4A184E0E20C7381314F7B483A2ABF7FB78C1B51E8DBFB861FD838A7FE8CABC4A7C80808EE000D98C4D2EC1C5ECBB2C43EA78BF5EE88EA; _ga_3Q0DVSGN10=GS1.1.1708325493.5.1.1708325499.54.0.0; Hm_lvt_866c9be12d4a814454792b1fd0fed295=1706748426,1708325490,1708391519,1708501567; Hm_lpvt_866c9be12d4a814454792b1fd0fed295=1708501575; _ga_M95P3TTWJZ=GS1.1.1708501566.271.1.1708501577.0.0.0; _ga_C2LFP3RFGH=GS1.1.1708501582.266.1.1708502460.0.0.0'
}

# 上传文件需要构造字典
files = {
    # 文件名字,二进制内容,标注图片类型
    'imageFile':("1.png", open('1.png', 'rb'), "image/jpeg"),
    'host': 'www.cnblogs.com',
    'uploadType': 'Paste'
}

res = requests.post('https://upload.cnblogs.com/imageuploader/CorsUpload',headers=header,files=files)
print(res.text)

结果:

九 selenium基本使用

  • 由于requests不能 执行js---》逐个分析 ajax请求--》模拟发送获取数据
    • 使用requests爬取的数据 很大概率跟在浏览器中看到的不一样
    • requests不能执行js
  • selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题
  • selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如跳转、输入、点击、下拉等,来拿到网页渲染之后的结果(跟咱们在浏览器看到的完全一致--》可见即可爬),可支持多种浏览器
# 这个模块:既能发请求,又能解析,还能执行js

# selenium 会做web方向的自动化测试,可以操作浏览器,模拟人的 行为
# appnium 会做 app方向的自动化测试

9.1 selenium的使用

1 下载浏览器驱动:

确认好,我们要驱动什么浏览器(谷歌[以它为例],火狐,ie。。)

如果谷歌是:122.0.6261.57这个版本,下它
https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/119.0.6045.105/win64/chromedriver-win64.zip

跟浏览器型号和版本一一对应的
ie,火狐,谷歌:谷歌为例
谷歌浏览器有很多版本:跟版本一一对应,谷歌版本119,需要驱动也是119的
下载一个浏览器驱动:
    	122.0.6261.58 ----》https://googlechromelabs.github.io/chrome-for-testing/
        win平台是:chromedriver.exe

2.把驱动放在浏览器根路径下:

3 安装 selenium模块

pip install selenium

4 写python代码,操作浏览器

import time
from selenium import webdriver

# 跟人操作浏览器一样,打开了谷歌浏览器,拿到浏览器对象
bro=webdriver.Chrome()
# 在地址栏中输入地址
bro.get('https://www.baidu.com')

time.sleep(3)

bro.close()

9.2 模拟登录

import time

from selenium import webdriver
from selenium.webdriver.common.by import By

bro = webdriver.Chrome()

# 1.打开百度
bro.get('https://www.baidu.com')

# 2.设置等待,从页面中找标签,如果找不到,就等待,
bro.implicitly_wait(10)

# 最大化
bro.maximize_window()

# print(bro.page_source)  # 当前页面的html内容

# 3.找到登录按钮--->选择器--->css选择器
# bro.find_element(by='By.NAME',value='tj_login') 按照name找
# a_login=bro.find_element(by=By.ID,value='s-top-loginbtn')
a_login = bro.find_element(by=By.LINK_TEXT, value='登录')  # 找a标签的链接文字

time.sleep(3)
# 4.点击找到的按钮
a_login.click()

# 找到短信登录,点击
sms_login=bro.find_element(by=By.CSS_SELECTOR,value='#TANGRAM__PSP_11__changeSmsCodeItem')
sms_login.click()
time.sleep(2)


# 找到账号登录,点击
user_login=bro.find_element(by=By.CSS_SELECTOR,value='#TANGRAM__PSP_11__changePwdCodeItem')
user_login.click()
time.sleep(1)

username = bro.find_element(by=By.ID,value='TANGRAM__PSP_11__userName')
# 往输入框中输入名字
username.send_keys('wrx@qq.com')
password = bro.find_element(by=By.ID,value='TANGRAM__PSP_11__password')
password.send_keys('wrx@qq.com')
time.sleep(1)

agree = bro.find_element(By.ID,'TANGRAM__PSP_11__isAgree')
agree.click()
time.sleep(1)

submit = bro.find_element(By.ID,'TANGRAM__PSP_11__submit')
submit.click()
time.sleep(1)

bro.close()


9.3 selenium其它用法

1 无头浏览器

# 如果我们做爬虫,我们只是为了获取数据,不需要非有浏览器在显示--->隐藏浏览器图形化界面

import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

chrome_options = Options() # 得到实例化对象

chrome_options.add_argument('blink-settings=imagesEnabled=false') #不加载图片, 提升速度
chrome_options.add_argument('--headless') #浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
bro = webdriver.Chrome(options=chrome_options) #按照上面的配置浏览器

bro.get('https://www.cnblogs.com/liuqingzheng/p/16005896.html')

print(bro.page_source)
time.sleep(3)
bro.close()

2 搜索标签

import time
from bs4 import BeautifulSoup

from selenium import webdriver
from selenium.webdriver.common.by import By


from selenium.webdriver.chrome.options import Options
chrome_options = Options() # 得到实例化对象
chrome_options.add_argument('blink-settings=imagesEnabled=false') #不加载图片, 提升速度
chrome_options.add_argument('--headless') #浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
bro = webdriver.Chrome(options=chrome_options) #按照上面的配置浏览器

bro.get('https://www.cnblogs.com/liuqingzheng/p/16005896.html')

### 虽然学了bs4,但是不建议使用了--->建议使用selenium提供的查找
# soup = BeautifulSoup(bro.page_source,'html.parser')
# print(soup.find(title='下载哔哩哔哩视频').attrs.get('href'))

### selenium提供的查找

"""
selenium内置的
By.ID  根据id号查找标签
By.NAME  根据Name属性
By.TAG_NAME 根据标签名查找
By.CLASS_NAME 根据类名查找
By.LINK_TEXT  a标签文字
By.PARTIAL_LINK_TEXT  a标签文字模糊匹配

selenium通用的
By.CSS_SELECTOR  按css选择器找
By.XPATH    按xpath找
"""

div=bro.find_element(By.ID,'cnblogs_post_body')
### 找到标签后,获取标签属性,文本,位置,大小等
print(div.get_attribute('class')) # 找到tag标签的src属性
print(div.id)  # 这个id不是id号,不需要关注
print(div.location) # 在页面中的位置,x轴,y轴
print(div.tag_name) # 标签名
print(div.size)  # 标签大小,也就是x轴
print(div.text)  # 文本内容

# 找到页面所有的div
divs = bro.find_elements(By.TAG_NAME,'div')

# 按类名找到其文字内容
# div=bro.find_element(By.CLASS_NAME,'postDesc').text

# 按css选择器找
# div =bro.find_element(By.CSS_SELECTOR,'.postDesc').text
# div=bro.find_element(By.CSS_SELECTOR,'#topics > div > div.postDesc').text

# 按照xpath选择--->专门学xpath的语法
div=bro.find_element(By.XPATH,'//*[@id="topics"]/div/div[3]').text


time.sleep(1)
bro.close()

案例

import time

from selenium import webdriver
from selenium.webdriver.common.by import By

bro = webdriver.Chrome()
bro.get('https://kyfw.12306.cn/otn/resources/login.html')
bro.implicitly_wait(10)
bro.maximize_window()
a = bro.find_element(By.LINK_TEXT, '扫码登录')
a.click()
time.sleep(1)
bro.save_screenshot('main.png')

# 打印标签位置和坐标
img=bro.find_element(By.ID,'J-qrImg')
print(img.location)
print(img.size)

time.sleep(5)
bro.close()
posted @ 2023-11-08 20:58  瓜瓜不甜  阅读(45)  评论(0)    收藏  举报