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

來源:互聯網
上載者:User

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

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

首先是網頁的內容

查看網頁源碼後發現可以使用BeautifulSoup來擷取文檔的標題和內容,並儲存為doc檔案。

這裡需要使用from bs4 import BeautifulSoup  來匯入該模組

具體代碼如下:

# 輸出所在網址的內容
from bs4 import BeautifulSoupdef 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 *********** 進行安裝,

注意:

  *************代表的是安裝檔案的全稱。

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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.