爬虫

1 bs4介绍,遍历文档树

# beautifulsoup4 从HTML或XML文件中提取数据的python库
# 用它来解析爬回来的xml

# 安装:pip install beautifulsoup4
	pip install lxml  # 解析库
    
# soup=BeautifulSoup('要解析的内容str类型', 'html.parser/lxml')    

1.1 bs4的遍历文档树

from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title">
lqz
<b>The Dormouse's story</b>
</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" name='lqz'>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, 'lxml')

# 1 美化,不是标准xml,完成美化
# print(soup.prettify())

# 2 遍历文档树---》通过 . 来遍历
# print(soup.html.body.p)  # 一层一层找
# print(soup.p)  # 跨层 只找第一个

# 3 获取标签的名称
# print(soup.a.name)

# 4 获取标签的属性---》属性字典
# print(soup.a.attrs['href'])
# print(soup.a.attrs.get('class'))  # class 会有多个 ['sister']
# print(soup.a.attrs.get('name'))

# 5 获取标签的内容
# text 获取该标签内部子子孙孙所有标签的文本内容
# print(soup.p.text)
# string p下的文本只有一个时,取到,否则为None
# print(soup.p.string)
# strings
# print(list(soup.p.strings))  # generator生成器 用list转

# 6 嵌套选择
# print(soup.html.body)

# -----了解
# 7 子节点、子孙节点
# print(soup.body.contents)  # p下所有子节点,只取一层
# print(list(soup.p.children))  # list_iterator得到一个迭代器,包含p下所有子节点  只取一层
# print(list(soup.body.descendants))  # generator 子子孙孙

# 8 父节点、祖先节点
# print(soup.a.parent)  # 获取a标签的父节点  直接父亲
# print(list(soup.a.parents))  # 找到a标签所有的祖先节点,父亲的父亲,父亲的父亲的父亲...
# 9 兄弟节点
# print(soup.a.next_sibling)  # 下一个兄弟
# print(soup.a.previous_sibling)  # 上一个兄弟
# print(list(soup.a.next_siblings))  # 下面的兄弟们=》生成器对象
# print(list(soup.a.previous_siblings))  # 上面的兄弟们=》生成器对象

2 bs4搜索文档树

# find   find_all

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p id="my p" class="title"><b id="bbb" class="boldest">The Dormouse's story</b>
</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>
"""

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_doc, 'lxml')

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

# 1 字符串----》查询的条件是字符串
# res=soup.find_all(name='p')
# res=soup.find_all('p')
# print(res)
# 类名叫sister的所有标签
# res=soup.find_all(class_='sister')
# print(res)

# id 叫link1的标签
# res=soup.find_all(id='link1')
# print(res)

# 文本内容叫Elsie的父标签
# res=soup.find(text='Elsie').parent
# print(res)

# 另一种方式
# res=soup.find_all(attrs={'class':'sister'})
# res=soup.find_all(attrs={'id':'link1'})
# print(res)

# 2 正则表达式
# import re
# res=soup.find_all(id=re.compile('^l'))
# res=soup.find_all(class_=re.compile('^s'))
# print(res)

# 3 列表
# res=soup.find_all(id=['link1', 'link2'])
# print(res)
# print(soup.find_all(name=['a', 'b']))
# print(soup.find_all(['a', 'b']))

# 4 True
# res=soup.find_all(id=True)  # 所有有id的标签
# res=soup.find_all(href=True)  # 所有有href的标签
# res=soup.find_all(class_=True)  # 所有有class的标签

# 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))

2.1 find的其他参数

name
class_
id
text
attrs
------
limit:限制调试,find_all用的   find本质是find_all  limit=1
recursive: 查找的时候,是只找第一层还是子子孙孙都找,默认是True,子子孙孙都找
# limit 参数
# res=soup.find_all(href=True,limit=2)
# print(res)

# recursive 查找的时候,是只找第一层还是子子孙孙都找
# res=soup.find_all(name='b', recursive=False)
# res=soup.find_all(name='b')

# 建议遍历和搜索一起用
res=soup.html.body.p.find_all(name='b', recursive=False)
print(res)

2 css选择器

# 之前学过css选择器,可以很复杂
	.类名
    id
    p
# 咱们只学了bs4,以后可能见到别的解析器(lxml)---》他们都会支持css选择器,也会支持xpath
# bs4 支持css选择器
# html_doc = """
# <html><head><title>The Dormouse's story</title></head>
# <body>
# <p class="title">
#     <b>The Dormouse's story</b>
#     Once upon a time there were three little sisters; and their names were
#     <a href="http://example.com/elsie" class="sister" id="link1">
#         <span>Elsie</span>
#     </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>;
#     <div class='panel-1'>
#         <ul class='list' id='list-1'>
#             <li class='element'>Foo</li>
#             <li class='element'>Bar</li>
#             <li class='element'>Jay</li>
#         </ul>
#         <ul class='list list-small' id='list-2'>
#             <li class='element'><h1 class='yyyy'>Foo</h1></li>
#             <li class='element xxx'>Bar</li>
#             <li class='element'>Jay</li>
#         </ul>
#     </div>
#     and they lived at the bottom of a well.
# </p>
# <p class="story">...</p>
# """
from bs4 import BeautifulSoup
# soup=BeautifulSoup(html_doc, 'lxml')

# select内写css选择器
# print(soup.select('.sister'))
# print(soup.select('#link1'))
# print(soup.select('#link1 span'))

# 终极大招---》如果不会写css选择器,可以复制

import requests
res=requests.get('https://www.w3school.com.cn/css/css_selector_attribute.asp')
soup=BeautifulSoup(res.text, 'lxml')
print(soup.select('#intro > p:nth-child(1) > strong'))
print(soup.select('#intro > p:nth-child(1) > strong')[0].text)

3 selenium基本使用

# selenium
selenium最初是一个自动化测试工具,而爬虫中使用它主要是为了解决requests无法直接执行JavaScript代码的问题

selenium本质是通过驱动浏览器,完全模拟浏览器的操作,比如跳转、输入、点击、下拉等,来拿到网页渲染之后的结果,可支持多种浏览器

# 使用步骤:
	1 下载selenium
    2 操作浏览器:分不同浏览器,需要下载不同浏览器驱动
    	-用谷歌---》谷歌浏览器驱动:https://registry.npmmirror.com/binary.html?path=chromedriver/
        -跟谷歌浏览器版本要对应  111.0.5563.65:
    3 下载完的驱动,放在项目路径下
    4 写代码,控制谷歌浏览器
    from selenium import webdriver
    import time
    bro = webdriver.Chrome(executable_path='chromedriver.exe')  # 打开一个谷歌浏览器
    bro.get('https://www.baidu.com/s?wd=%E7%BE%8E%E5%A5%B3')  # 在地址栏中输入地址
    print(bro.page_source)  # 当前页面的内容  (html格式)
    with open('1.html', 'w', encoding='utf-8') as f:
        f.write(bro.page_source)
    time.sleep(5)
    bro.close()  # 关闭浏览器

4 无界面浏览器

from selenium import webdriver
import time

from selenium.webdriver.chrome.options import Options
# 隐藏浏览器的图形化界面,但是数据还拿到了
chrome_options = Options()
chrome_options.add_argument('window-size=1920x3000')  # 指定浏览器分辨率
chrome_options.add_argument('--hide-scrollbars')  # 隐藏滚动条,应对一些特殊页面
chrome_options.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片,提升速度
chrome_options.add_argument('--headless')  # 浏览器不提供可视化页面,Linux下如果系统不支持可视化不加这条会启动失败
# chrome_options.binary_location = rC:\Program Files (x86)\Google\Chrome\Application\chrome.exe"  # 手动指定使用的浏览器位置

bro = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=chrome_options)  # 打开一个谷歌浏览器
# 隐藏浏览器的图形化界面,但是数据还能拿到
bro.get(bro.page_source)  # 当前页面的内容  (html格式)
time.sleep(5)
bro.close()  # 关闭浏览器

4.1 模拟登录百度

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

bro = webdriver.Chrome(executable_path='chromedriver.exe')  # 打开一个谷歌浏览器
bro.get('https://www.baidu.com')
# 加入等待,找标签,如果找不到,就等待x秒,如果还找不到就报错
bro.implcitly_wait(10)  # 1等待
# 从页面中找到登录 a标签,点击它
# By.LINK_TEXT  按a标签文本内容找
btn = bro.find_element(by=By.LINK_TEXT, value='登录')
# 点击它
btn.click()

# 找到按账号登录的点击按钮,有id,优先用id,因为唯一 TANGRAM__PSP_11__changePwdCodeItem
btn_2 = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__changeSmsCodeItem')
btn_2.click()
time.sleep(1)

btn_2 = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__changePwdCodeItem')
btn_2.click()
time.sleep(1)

name = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__userName')
password = bro.find_element(by=By.ID, value='TANGRAM__PSP_11__password')
name.send_keys('12312412@qq.com')
password.send_keys('1234')
time.sleep(1)

submit=bro.find_element(by=By.ID, value='TANGRAM__PSP_11__submit')
submit.click()
time.sleep(2)
bro.close()  # 关闭浏览器

5 selenium其他用法

5.0 查找标签

# 两个方法
bro.find_element  找一个
bro.find_elements  找所有

# 可以按id,标签名,name属性名,类名,a标签的文字,a标签的文字模糊匹配,css选择器,xpath
# input_1 = bro.find_element(by=By.ID, value='wd')  # 按id找
# input_1 = bro.find_element(by=By.NAME, value='wb')  # name属性名
# input_1 = bro.find_element(by=By.TAG_NAME, value='input')  # 可以按标签名字找
# input_1 = bro.find_element(by=By.CLASS_NAME, value='s_ipt')  # 可以按类名
# input_1 = bro.find_element(by=By.LINK_TEXT,value='登录')  # 可以按a标签内容找
# input_1=bro.find_element(by=By.PARTIAL_LINK_TEXT,value='录') # 可以按a标签内容找
# input_1 = bro.find_element(by=By.CSS_SELECTOR, value='#su')  # 可以按css选择器

5.1 获取位置属性大小,文本

print(tag.get_attribute('src'))  # 用的最多
tag.text  # 文本内容
#获取标签ID,位置,名称,大小(了解)
print(tag.id)
print(tag.location)
print(tag.tag_name)
print(tag.size)

5.2 等待元素被加载

# 代码执行很快,有的标签没来得及加载,直接查找就会报错,设置等待时间
# 隐士等待:所有标签,只要去找,找不到就遵循 等10s的规则
	bro.implicitly_wait(10)
# 显示等待:需要给每个标签绑定一个等待,麻烦    

5.3 元素操作

# 点击
tag.click()

# 输入内容
tag.send_keys()

# 清空内容
tag.clear()


# 浏览器对象 最大化
bro.maximize_window() 
#浏览器对象  截全屏
bro.save_screenshot('main.png') 

5.4 执行js代码

bro.execute_script('alert("美女")')  # 引号内部的相当于 用script标签包裹了


# 可以干的事
	-获取当前访问的地址  window.location
    -打开新的标签
    -滑动屏幕--》bro.execute_script('scrollTo(0,document.documentElement.scrollHeight)')
    -获取cookie,获取定义的全局变量

5.5 切换选项卡

import time
from selenium import webdriver

browser=webdriver.Chrome(executable_path='chromedriver.exe')
browser.get('https://www.baidu.com')
browser.execute_script('window.open()')

print(browser.window_handles) #获取所有的选项卡


browser.switch_to.window(browser.window_handles[1])
browser.get('https://www.taobao.com')
time.sleep(2)
browser.switch_to.window(browser.window_handles[0])
browser.get('https://www.sina.com.cn')
browser.close()

5.6 浏览器前进后退

import time
from selenium import webdriver

browser=webdriver.Chrome(executable_path='chromedriver.exe')
browser.get('https://www.baidu.com')
browser.get('https://www.taobao.com')
browser.get('http://www.sina.com.cn/')

browser.back()
time.sleep(2)
browser.forward()
browser.close()

5.7 异常处理

import time
from selenium import webdriver

browser=webdriver.Chrome(executable_path='chromedriver.exe')
try:
except Exception as e:
    print(e)
    
finally:
    browser.close()
posted @ 2023-03-20 14:38  理塘丁真1!5!  阅读(17)  评论(0编辑  收藏  举报