day 5 爬虫 - selenium的使用

day 5 爬虫 - selenium的使用

用selenium使用谷歌浏览器需要配置谷歌浏览器的webdriver ,不同浏览器后续使用方法也不同

from selenium.webdriver import Chrome
# 创建浏览器对象,并且打开一个空的页面
b = Chrome()
b.get('https://www.baidu.com/')

# input()   # 打开网页不关闭,没有input,网页打开后会自动关闭
1. selenium的基本操作
from selenium.webdriver import Chrome

1)创建浏览器对象

b = Chrome()

2)打开网页(需要拿一个网页的数据,就打开那个页面对应的页面地址)

b.get('https://movie.douban.com/top250?start=0&filter=')

3) 获取网页源代码(获取的是当前b.get(地址)指定地址页面的源代码)
不管以什么样的方式更新了界面内容,page_source的内容也会更新

print(b.page_source)  # 获取的是top250的代码
# input('结束:') # 在控制台输入任意字符再关闭页面

print('=================================================================')
b.get('https://www.baidu.com/')
print(b.page_source)
2. selenium的翻页方法
from selenium.webdriver import Chrome

1)方法1:找到不同页的地址变化规律,利用循环实现多页数据的请求

b = Chrome()

for i in range(0,226,25):
    b.get(f'https://movie.douban.com/top250?start={i}&filter=')
    print(b.page_source)
    print(f'------------------ 第{(i+25)//25}页爬取完毕!----------------------')

2)方法2:点击翻页按钮,刷新页面内容,在刷新后获取网页源代码

b = Chrome()
# 只需打开首页(只要最开始的b.get())
b.get(f'https://www.zhipin.com/chengdu/?sid=sem_pz_bdpc_dasou_title')


for _ in range(5):
    print(b.page_source)
    # 点击下一页按钮
    # find_element 返回标签对象
    # find_elements 返回列表
    # 获取按钮
    next = b.find_element(By.CLASS_NAME,'next') # 通过classanem直接写属性值即可
    # 点击按钮
    next.click()

方法2涉及的知识点:
浏览器对象.b.find_element(获取方式,数据) - 返回符合条件的第一个标签,结果是标签对象
浏览器对象.b.find_elements(获取方式,数据) - 返回符合条件的所有标签,形式为列表,每个元素是一个标签对象

  1. 获取方式:
    By.ID — 通过ID属性值获取标签
    By.CLASS_NAME — 通过clss属性值获取标签
    By.CSS_SELECTOR — 通过css选择器获取标签
    By.LINK_TEXT — 通过a标签的标签内容获取标签内容
    By.LINK_TEXT — 通过获取标签
search = b.find_element(By.ID,'key')  # 获取ID属性值为key的标签

获取标签内容为'便宜包邮'的a标签
a1 = b.find_element(By.LINK_TEXT,'Java')  # '便宜包邮'是a标签的标签内容
a1.click()
input('结束:')

# 获取标签内容包含'进口'的a标签
a2 = b.find_element(By.PARTIAL_LINK_TEXT,'算法')
a2.click()
input('结束:')
"""
2. 操作标签
# 1). 输入框输入内容:输入框对应的标签.send_keys(内容)
# 2). 点击标签: 标签对象.click()
# 3). 切换选项卡(点击网页某地后,出现了新的单独的网页则需要切换选项卡,
        因为会默认一直指向原来的网页窗口,即使出现新窗口,它仍指向原来死的)
        切换到新窗口后若想回原来窗口也需要用切换,否则即使关闭新窗口,它指向的仍是新窗口
"""
3. 滚动网页
# 滚动页面获取数据
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
import time
b=Chrome()
b.get('https://search.jd.com/Search?keyword=%E7%94%B5%E9%A5%AD%E7%85%B2&enc=utf-8&suggest=1.def.0.SAK7|MIXTAG_SAK7R,SAK7_M_AM_L5393,SAK7_S_AM_R,SAK7_D_HSP_R,SAK7_SC_PD_R,SAK7_SM_PB_R,SAK7_SM_PRK_R,SAK7_SM_PRC_LC,SAK7_SM_PRR_R,SAK7_SS_PM_R,tsabtest_base64_U2VhcmNobGlzdF80MzkyfG1pZGRsZUhhdmU_tsabtest|&wq=%E7%94%B5&pvid=74e1f7618d804df99aa4cb8ee0b6911f')
time.sleep(2)
# input('人工滚动完成:')

# ========= 用代码控制浏览器滚动 ==========
# js中页面滚动的代码:window.scrollBy(x方向的偏移量,y方向的偏移量)
# b.execute_script('window.scrollBy(0,1000)') # 不能一次滚动距离过长,可以多次滚动,等待加载
for x in range(10):
    b.execute_script('window.scrollBy(0,800)')
    time.sleep(2)

result = b.find_elements(By.CSS_SELECTOR,'#J_goodsList>ul>li')
print(len(result))


input('结束:')
作业:爬取京东商品数据
from re import findall,search,sub
from csv import reader,writer
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
import time
from bs4 import BeautifulSoup

b = Chrome()
b.get('https://search.jd.com/Search?keyword=%E5%BA%8A%E5%B8%98%E8%9A%8A%E5%B8%90%E4%B8%80%E4%BD%93%E5%BC%8F&enc=utf-8&suggest=2.def.0.SAK7|MIXTAG_SAK7R,SAK7_M_AM_L5393,SAK7_S_AM_R,SAK7_D_HSP_R,SAK7_SC_PD_R,SAK7_SM_PB_R,SAK7_SM_PRK_R,SAK7_SM_PRC_LC,SAK7_SM_PRR_R,SAK7_SS_PM_R,tsabtest_base64_U2VhcmNobGlzdF80MzkyfG1pZGRsZUhhdmU_tsabtest|&wq=chuanglianwenz&pvid=884efb249f304ace8e27bdbe92fd98c7')
time.sleep(2)

def get_onepage():
    for i in range(10):
        b.execute_script('window.scrollBy(0,800)')
        time.sleep(2)
    soup = BeautifulSoup(b.page_source, 'lxml')
    all_list = soup.select('li.gl-item')

    for i in all_list:
        price = i.select_one('div.p-price i').text
        # print(price)

        words = i.select_one('div.p-name.p-name-type-2 em').text
        word = sub(r'[^[\u4e00-\u9fa5]]','',str(words))
        # print(word)

        comment = i.select_one('div.p-commit a').text
        # print(comment)

        store_name = i.select_one('div.p-shop a').text
        # print(store_name)

        store_lian = i.select_one('div.p-shop a').attrs['href']
        # print(store_lian)

        goods_lian = i.select_one('div.p-img a').attrs['href']
        print(goods_lian)

        with open('files/jd.csv','a',encoding='utf-8',newline='') as f:
            w1 = writer(f)
            w1.writerow([store_name,word,comment,price,goods_lian,store_lian])

        print('======================  一页获取结束  =======================')



def get_jd_pages(n:int):
    with open('files/jd.csv', 'w', encoding='utf-8', newline='') as f:
        w1 = writer(f)
        w1.writerow(['店名', '基本信息', '评价人数', '价格', '商品链接', '店铺链接'])
    for _ in range(n):
        get_onepage()
        result = b.find_element(By.CLASS_NAME,'pn-next')
        result.click()

if __name__ == '__main__':
    get_jd_pages(3)
    input()
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值