「爬虫03」bs4&selenium

发布时间 2023-07-13 01:37:32作者: 雀雀飞了

1 爬取新闻

# 1 爬取网页---requests
# 2 解析 
---xml格式,用了re匹配的[xml包含html,html是xml的一种]
---html,bs4,lxml。。。
---json:
	-python :内置的
	-java : fastjson---》漏洞
	-java:  谷歌  Gson
	-go :内置 基于反射,效率不高
        
import requests
# pip3.8 install beautifulsoup4
# pip3.8 install lxml
from bs4 import BeautifulSoup
# 1. 链接mysql(0407)
# 此时python链接mysql,python就是一个客户端
# 既然是客户端,那就需要链接服务端,保证服务端的正常运行
import pymysql
conn=pymysql.connect(
    user='root',
        password="123",
        host='127.0.0.1',
        database='cars'  # 需要去数据库创建表,无法在此创建
)
# 2. 获取一个游标
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
# 返回的查询结果以字典的形式表示,其中列名作为字典的键,对应的值为每行的数据。
res = requests.get('https://www.autohome.com.cn/news/1/#liststart')
# 1 解析的字符串  2 解析器(html.parser内置的),第三方lxml,额外安装,否则报错
# soup=BeautifulSoup(res.text,'html.parser')  

# 1 解析的字符串  2 解析器(html.parser内置的),第三方  lxml ,额外安装,否则报错
soup = BeautifulSoup(res.text, 'lxml')  

# find:找一个  和 find_all:找所有

ul_list = soup.find_all(name='ul', class_='article')
print(len(ul_list))
for ul in ul_list:
    li_list = ul.find_all(name='li')
    print(len(li_list))
    for li in li_list:
        h3 = li.find(name='h3')
        # print(h3)
        if h3:
            title = h3.text
            url = 'https:' + li.find(name='a').attrs.get('href')
            desc = li.find(name='p').text
            img = li.find(name='img').attrs.get('src')

            print('''
            新闻标题:%s
            新闻图片:%s
            新闻地址;%s
            新闻摘要:%s
            '''%(title,img,url,desc))
            # 图片保存到本地
            # 数据入库
# 3 执行sql语句
						try:
            	cursor.execute('insert into news (title,img,url,`desc`) values (%s,%s,%s,%s)',args=[title,img,url,desc])  # 这样不会有xss攻击
            # cursor.execute('insert into news (title,img,url,`desc`) values (%s,%s,%s,%s)'%(title,img,url,desc))  # 这样会有xss攻击
# 4 二次确认,除查询之外的都要用
            	conn.commit()
  					except Exception as e:
     			  # 发生异常时进行回滚
      				conn.rollback()
        			print("An error occurred:", str(e))
  
  					# 获取查询结果
            results = cursor.fetchall()

            # 遍历结果
            for row in results:
                print(row)

       # 关闭游标和数据库连接
      cursor.close()
      conn.close()

2 bs4介绍遍历文档树

# 解析器bs4和lxnml用来解析html格式,就是在html中查找元素的第三方包

BeautifulSoup(markup, "html.parser")
# Python的内置标准库 执行速度适中 文档容错能力强;Python 2.7.3 or 3.2.2)前 的版本中文档容错能力差

BeautifulSoup(markup, "lxml")
# 速度快 文档容错能力强;需要额外安装 pip install lxml
from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story<span>lqz</span></b><b>adfasdf<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>
"""

soup = BeautifulSoup(html_doc, 'lxml')
print(soup.prettify())  # 对其做美化
     

# 遍历文档树:即直接通过标签名字选择,特点是选择速度快,但如果存在多个相同的标签则只返回第一个

# 1、用法   通过 .  遍历
a=soup.html.body.a
a=soup.a
print(a)


# 2、获取标签的名称
# soup.a  是对象
a=soup.a.name
print(a)


# 3、获取标签的属性
# a=soup.a.attrs 是一个字典有a的所有属性
a=soup.a.attrs.get('id')
print(a)
a=soup.a.attrs.get('href')
print(a)


# 4、获取标签的内容---文本内容
p=soup.p.text   # text 会把当前标签的子子孙孙的文本内容都拿出来,拼到一起
# print(p)
s1=soup.p.string  # 当前标签有且只有自己(没有子标签),把文本内容拿出来
# print(s1)  # None
s1=list(soup.p.strings)  # generator 把子子孙孙的文本内容放到生成器中
# print(s1)


# 5、嵌套选择  . 完后可以继续再 .
# print(soup.head.title.text)


# 6、子节点、子孙节点
print(soup.p.contents)  # p下所有直接子节点
print(list(soup.p.children))  # 得到一个迭代器,包含p下所有直接子节点
print(list(soup.p.descendants))  # 生成器,子子孙孙


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


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

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

3 bs4搜索文档树

# find:找到最符合的第一个     find_all:找到所有
五种过滤器: 字符串、正则表达式、列表、True、方法
from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b class ='baby'>The Dormouse's story<span>lqz</span></b><b>adfasdf<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" xx="xx">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" name="zzz">Tillie</a>;
and they lived at the bottom of a well.</p>

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

soup = BeautifulSoup(html_doc, 'lxml')
# 五种过滤器: 字符串、正则表达式、列表、True、方法

# 1 字符串    通过字符串查找
a=soup.find(name='a')
a=soup.find_all(name='a',class_='sister')
a=soup.find_all(name='a',id='link1')
a=soup.find(text='Elsie').parent
a=soup.find(href='http://example.com/elsie')   # 括号中可以写 name,id,class_,href,text,所有属性
a=soup.find(xx='xx')   # 括号中可以写 name:标签名,id,class_,href,text,所有属性
a=soup.find(attrs={'class':'sister'})  # 可以通过attrs传属性
a=soup.find(attrs={'name':'zzz'})  # 可以通过attrs传属性
print(a)



# 2 正则表达式
import re
a = soup.find_all(class_=re.compile('^b'))
# 找出所有有链接的标签
a = soup.find_all(href=re.compile('^http'))
a = soup.find_all(name=re.compile('^b'))
# 打印出所有图片地址
print(a)


# 3 列表
a = soup.find_all(name=['b','body','span'])  # or
a = soup.find_all(class_=['sister','title'])
print(a)


# 4 True
a=soup.find_all(href=True)
a=soup.find_all(src=True,name='img')
print(a)


# 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的标签

3.2 其他用法


# find本质就是find_all:find的参数,就是find_all的参数,但是find_all比find多

# recursive=True:是否递归查找,默认是True,如果写成False,只找第一层
a=soup.find_all(name='html',recursive=False)
# 速度很快,联合遍历文档树使用
a=soup.html.p.find(name='b',recursive=False)
print(a)


# limit=None  限制找几条
a=soup.find_all(name='a',limit=1)
print(a)

4 css选择器

from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b class ='baby'>The Dormouse's story<span>lqz</span></b><b>adfasdf<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" xx="xx">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" name="zzz">Tillie</a>;
and they lived at the bottom of a well.</p>

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

soup = BeautifulSoup(html_doc, 'lxml')
# css选择器
'''
div
.类名
#id
div a  # div下的子子孙孙中得a
div>a  # div直接子节点a
'''

res=soup.select('.sister')
res=soup.select('#link1')
res=soup.p.find(name='b').select('span')
print(res)


# 以后,基本所有的解析器都会支持两种解析:css,xpath,都可以去页面中复制,在浏览器--》F12--》选到所需的elements--〉右键copy--》selector or xpath

import requests

res=requests.get('http://it028.com/css-selectors.html')
# res.encoding=res.apparent_encoding 从页面解析编码方式
res.encoding='utf-8'
# print(res.text)
soup=BeautifulSoup(res.text,'lxml')
res=soup.select('#content > table > tbody > tr:nth-child(14) > td:nth-child(3)')
# //*[@id="content"]/table/tbody/tr[14]/td[3]
print(res)

5 selenium基本使用

# requests 发送请求,不能加载ajax 
# selenium:pc端直接操作浏览器,不是直接发送http请求,而是用代码控制模拟人操作浏览器的行为,js会自动加载-----》实现了可见即可爬
# 无头:不打开图形化界面----》进程在后台运行
# appnium :移动端直接操作手机

# 使用步骤(操作什么浏览器:1 谷歌(为例) 2 ie 3 Firefox)
1 下载谷歌浏览器驱动(跟浏览器版本一致)
    	-https://registry.npmmirror.com/binary.html?path=chromedriver/
      -浏览器版本:114.0.5735.198
      -驱动版本对应
      -放到项目路径下
        
2 写代码
        # pip3.8 install selenium
        from selenium import webdriver
        import time
        from selenium.webdriver.common.by import By
        from selenium.webdriver.common.keys import Keys # 键盘按键操作

        bro = webdriver.Chrome(executable_path='./chromedriver.exe')  # 指定驱动位置, 打开了浏览器,也可以不用写,已经被弃用了
				# 输入
        bro.get('https://www.baidu.com')

        time.sleep(1)
        # 有id优先用id找
        input_name = bro.find_element(by=By.ID, value='kw')
        # 往标签中写内容
        input_name.send_keys('性感美女诱惑')
        button=bro.find_element(By.ID,'su')
  			# 通过鼠标点击来实现搜索
        button.click()
        # 通过键盘enter实现搜索
        input_name.send_keys(Keys.ENTER)
        time.sleep(2)
        bro.close()
        
        

5.1 模拟登录百度

# pip3.8 install selenium

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

bro.implicitly_wait(10) #隐士等待---》找标签,如果找不到就先等,等10s,如果10s内,标签有了,直接往下执行,如果登录10s还没有,就报错
bro.maximize_window()
# 如果是a标签,可以根据a标签文字找

submit_login = bro.find_element(By.LINK_TEXT, '登录')
submit_login.click()

# 点击短信登录
sms_login = bro.find_element(By.ID, 'TANGRAM__PSP_11__headerLoginTab')
sms_login.click()
time.sleep(1)
username_login = bro.find_element(By.ID, 'TANGRAM__PSP_11__changePwdCodeItem')

username_login.click()
time.sleep(1)

username=bro.find_element(By.ID,'TANGRAM__PSP_11__userName')
username.send_keys('306334678@qq.com')
password=bro.find_element(By.ID,'TANGRAM__PSP_11__password')
password.send_keys('asdfasdfasdfasfds')

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

time.sleep(3)
bro.close()

6 selenium其他用法

6.1 无头浏览器

# 无界面浏览器(一堆配置)
from selenium import webdriver
from selenium.webdriver.chrome.options import Options # 只针对谷歌浏览器
chrome_options = Options() # 实例化对象
chrome_options.add_argument('window-size=1920x3000') # 指定浏览器分辨率,决定了验证码图片大小和位置
chrome_options.add_argument('--disable-gpu') # 谷歌文档提到需要加上这个属性来规避bug
chrome_options.add_argument('--hide-scrollbars') # 隐藏滚动条, 应对一些特殊页面
chrome_options.add_argument('blink-settings=imagesEnabled=false') # 不加载图片, 提升速度
chrome_options.add_argument('--headless') # 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败



driver=webdriver.Chrome(chrome_options=chrome_options)
driver.get('https://www.baidu.com')
print(driver.page_sourec) # 当前页面内容,包括加载好的js
print('hao123' in driver.page_source)

driver.close() #切记关闭浏览器,回收资源

6.2 搜索标签

    #===============所有方法===================
    # 1、find_element_by_id
    # 2、find_element_by_link_text
    # 3、find_element_by_partial_link_text
    # 4、find_element_by_tag_name
    # 5、find_element_by_class_name
    # 6、find_element_by_name
    # 7、find_element_by_css_selector
    # 8、find_element_by_xpath
    # 强调:
    # 1、上述均可以改写成find_element(By.ID,'kw')的形式
    # 2、find_elements_by_xxx的形式是查找到多个元素,结果为列表

#===============示范用法===================
# pip3.8 install selenium

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

bro = webdriver.Chrome(executable_path='./chromedriver.exe')  # 打开了浏览器
bro.get('https://www.cnblogs.com/')
bro.implicitly_wait(10)

# bs4 find和find_all 也支持css

# selenium find_element和find_elements也支持css和xpath,前者找一个,后者找所有
# bro.find_element(by=By.ID)  #根据id号找一个
# bro.find_element(by=By.NAME)  #根据name属性找一个
res=bro.find_elements(by=By.TAG_NAME,value='div')  #根据标签名找一个
# bro.find_element(by=By.LINK_TEXT)  #根据a标签文字
# bro.find_element(by=By.PARTIAL_LINK_TEXT)  # 根据a标签文字模糊找
# bro.find_element(by=By.CLASS_NAME)  #根据类名

# bro.find_element(by=By.CSS_SELECTOR)  #根据css选择器找
# bro.find_element(by=By.XPATH)  #根据xpath
print(res)
# bro.find_elements() #找所有
bro.close()

6.3 等待元素被加载

#1、selenium只是模拟浏览器的行为,而浏览器解析页面是需要时间的(执行css,js),一些元素可能需要过一段时间才能加载出来,为了保证能查找到元素,必须等待

#2、等待的方式分两种:
隐式等待:在browser.get('xxx')前就设置,针对所有元素有效
显式等待:在browser.get('xxx')之后设置,只针对某个元素有效

#隐式等待:在查找所有元素时,如果尚未被加载,则等10秒
browser.implicitly_wait(10)

# 显示等待,等待切换按钮出现
# EC.presence_of_element_located() 方法用于指定等待条件,等待元素出现后再进行操作。
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素
tab_btn = WebDriverWait(browser, 10).until(
    EC.presence_of_element_located((By.CLASS_NAME, 'tab'))
)
tab_btn.click()

6.4 获取位置属性大小、文本

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By #按照什么方式查找,By.ID,By.CSS_SELECTOR
from selenium.webdriver.common.keys import Keys #键盘按键操作
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait #等待页面加载某些元素

browser=webdriver.Chrome()

browser.get('https://www.amazon.cn/')

tag = WebDriverWait(browser,10).until(EC.presence_of_element_located((By.ID,'cc-lm-tcgShowImgContainer')))

tag=browser.find_element(By.CSS_SELECTOR,'#cc-lm-tcgShowImgContainer img')

#获取标签属性,
print(tag.get_attribute('src'))

#获取标签ID,位置,名称,大小(了解)
print(tag.text) # 文本内容
print(tag.id) # 不是属性id,是selenium提供的id,无用
print(tag.location) # x、y坐标
print(tag.tag_name) 
print(tag.size) # 大小

browser.close()

作业

# 把验证码图片保存本地

https://www.chaojiying.com/apiuser/login/