Python爬蟲抓取 python tutorial中文版,保存為word


看到了中文版的python tutorial,發現是網頁版的,剛好最近在學習爬蟲,想着不如抓取到本地

首先是網頁的內容

查看網頁源碼后發現可以使用BeautifulSoup來獲取文檔的標題和內容,並保存為doc文件。

這里需要使用from bs4 import BeautifulSoup  來導入該模塊

具體代碼如下:

# 輸出所在網址的內容
from bs4 import BeautifulSoup
def introduce(url): res = requests.get(url) res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') title = soup.select('h1')[0].text content = '\n '.join([p.text.strip() for p in soup.select('.section')]) #print(title) #print(content)

接下來是使用for循環遍歷所有符合的內容以獲取目錄所指向的鏈接,所得到的鏈接是不完整的,故給其加上主站的鏈接,生成有效的url,儲存於列表address之中。這里我對比后使用了xpath來抓取目錄的地址,故用 from lxml import etree   導入該模塊

# 返回目錄所對應的地址
def get_url(selector):
    sites = selector.xpath('//div[@class="toctree-wrapper compound"]/ul/li')
    address = []
    for site in sites:
        directory = ''.join(site.xpath('a/text()'))
        new_url = site.xpath('a/@href')
        address.append('http://www.pythondoc.com/pythontutorial3/' + ''.join(new_url))
    return address

然后在主函數中調用get_url(),對其中的所有url遍歷,調用introduce()函數,輸出全部文本內容

def main(): 
    url = 'http://www.pythondoc.com/pythontutorial3/index.html#'
    html = requests.get(url)
    html.encoding = 'utf-8'
    selector = etree.HTML(html.text)
    introduce(url)
    url_list = get_url(selector)
    for url in url_list:
        introduce(url)

if __name__ == '__main__':
    main()

最后就是將輸出的東西寫到.doc中了,這里調用os模塊,將寫入文件的命令放置於introduce()函數中去

import os #將其放置於頂部

 with open('python.doc', 'a+', encoding='utf-8') as f:
        f.write(content)

至此,就完成了對中文版python tutorial內容的獲取,成功寫進本地文件中去,對於我這種經常性斷網斷點的人來說還是很不錯的!還可以放在手機里看,哈哈哈

 

對於bs4可以直接在命令行使用 pip install bs4 命令進行安裝

而在windows平台下 lxml 的安裝會出現許多錯誤,建議在windows下Python的擴展包網站下載對應版本的lxml.whl文件,之后在本地使用 pip install *********** 進行安裝,

注意:

  *************代表的是安裝文件的全稱。

  安裝的時候再命令行下一定要切換到下載文件所在的目錄下,否則會報錯。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM