python3 学习1(搜索关键字爬取一页word格式的百度文库并下载成文本)

本文介绍了一种使用Python的Selenium和BeautifulSoup库爬取百度文库文档的方法,包括定位搜索框、模拟搜索操作、解析文档内容及保存为本地文件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#coding: utf-8

from bs4 import BeautifulSoup
# -*- coding: UTF-8 -*-
from selenium import webdriver 

import time
browser = webdriver.Chrome()  
#打开百度文库的首界面   
browser.get("https://wenku.baidu.com/")   
#通过ID找网页的标签,找到搜索框的标签    
seek_input =  browser.find_element_by_id("kw")  
#设置搜索的内容    
seek_input.send_keys("2018财税新政策,有哪些调整") 
#找到搜索文档按钮    
seek_but = browser.find_element_by_id("sb")  
#并点击搜索文档按钮    
seek_but.click() 
#并点击搜索文档按钮    

html = browser.page_source
bf1 = BeautifulSoup(html, 'lxml')
result = bf1.find_all("a", class_="log-xsend tiaoquan act-xsend")

for result_table in  result:
    print ("-----标题----\n"+result_table.get('title'))#标题
    print("----链接----\n"+result_table.get('href'))#链接
    web=result_table.get('href')
    chromedriver_dir = 'D:\software\chormedriver\chromedriver.exe'
    options = webdriver.ChromeOptions()
    # 伪装成iPhone
    options.add_argument('--user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3')
    
    driver = webdriver.Chrome(chromedriver_dir, chrome_options=options)
    driver.get(web)
    # 向下滑动,到有“继续阅读”的位置停止
    foldpagewg = driver.find_elements_by_xpath("//div[@class='foldpagewg-root']")
    try:
        # 拖动到对应的位置
        driver.execute_script('arguments[0].scrollIntoView();', foldpagewg[-1])
        # 模拟点击,继续阅读
        continue_read = driver.find_element_by_xpath("//div[@class='foldpagewg-icon']")
        continue_read.click()
    except:
        print('此文章无需翻页!!!')
   
    attempts = 0
    success = True
    while attempts < 10 and success:
        try:
            # 向下滑动,到有“点击加载更多”的位置停止
            pagerwg = driver.find_elements_by_xpath("//div[@class='pagerwg-root']")
            # 拖动到可见的元素
            driver.execute_script('arguments[0].scrollIntoView();', pagerwg[-1])
    
            # 模拟点击,加载更多页面
            more_text = driver.find_element_by_xpath("//span[@class='pagerwg-arrow-lower']")
            more_text.click()
    
        except:
            success = False
            attempts += 1
            print('到底啦~~!请开始你的爬虫表演>.<')
    
        # 等待网页加载每次点击间隔2s
        time.sleep(3)
    
    html = driver.page_source
    bf1 = BeautifulSoup(html, 'lxml')
    result = bf1.find_all(class_='txt')
    texts_list = []  
    
    # 获得文章标题
    title = bf1.find_all('div', class_='doc-title')
     
    title = title[0].text.replace('\n' , "").replace('?' , "")
    filename = str(title) + '.txt'
    
    for each_result in result:
        bf2 = BeautifulSoup(str(each_result), 'lxml')
        texts = bf2.find_all('p')
        string=texts[0].getText()
        print(texts[0].getText())
        if string.find('。')>=0 :
                    texts_list.append(string+'\n')
        else:   
            texts_list.append(string)
            contentss = ''.join(texts_list)
        
    with open(filename, 'a', encoding='utf-8') as f:
        f.writelines(contentss)

//此爬取还是有缺陷,有的文章并不能爬取全,有的是vip才能爬取,博主还是个小白,仅作笔记用
                
        
        

Python是一种高级编程语言,拥有丰富的库和模块,可以方便地进行网络爬虫操作,用于从互联网上获取数据。关键字Python语言中具备特殊含义的单词,其中一个关键字是"爬取"。我们可以使用Python关键字来编写代码,实现从百度图片网站上爬取图片的功能。 首先,我们需要安装相关的Python库,例如"requests"用于发送网络请求,"beautifulsoup4"用于解析网页内容。然后,我们可以编写Python代码来实现爬取百度图片的功能。 首先,我们需要导入上述所需的库: ``` import requests from bs4 import BeautifulSoup ``` 接下来,我们需要定义一个函数,将要爬取的网址作为参数传入函数中。在函数中,我们使用"requests"库发送网络请求,获取网页的内容,然后使用"beautifulsoup4"库对网页内容进行解析。 ``` def crawl_baidu_images(url): response = requests.get(url) soup = BeautifulSoup(response.text, &#39;html.parser&#39;) ``` 接下来,我们需要通过分析百度图片网站的源代码,找到图片所在的标签和属性,然后使用"beautifulsoup4"库提供的方法来选取和提取图片。 ``` images = soup.find_all(&#39;img&#39;, class_=&#39;img-hover&#39;) for image in images: print(image[&#39;src&#39;]) ``` 最后,我们可以调用上述定义的函数,传入百度图片网站的网址,来执行爬取操作。 ``` crawl_baidu_images(&#39;http://image.baidu.com/&#39;) ``` 以上就是使用Python关键字实现爬取百度图片的简单示例代码。当然,实际的爬虫代码可能更加复杂,需要处理网页解析、数据存储等更多的细节。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你好龙卷风!!!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值