函式介紹
函式功能簡單介紹
庫函式介紹
import requests#請求網頁 from lxml import etree#對網頁進行決議
函式功能介紹
函式1
def getdata(url): html=requests.get(url).text # print(html) doc=etree.HTML(html)#構造xpath的決議物件 contents=doc.xpath('//*[@]/li') # print(contents) for content in contents: links=content.xpath('h2/a/@href') for link in links: hurl="https:"+link#小說某一章的網址 html=requests.get(hurl).text#獲取到源代碼 doc=etree.HTML(html)#構造xpath決議物件 title=doc.xpath('//*[@]/div/div[1]/h3/span[1]/text()') content=doc.xpath('//*[@]/p/text()') with open('novel/%s.txt'%title[0],mode='w',encoding='utf-8') as f: for abd in content: f.write(abd)
函式功能比較簡單,所以就沒有對其中的保存小說的函式進行封裝,有興趣的可以自己嘗試一下,
完整代碼
#獲取起點小說的爬蟲程式 #倒推法 import requests from lxml import etree url="https://book.qidian.com/info/1979049/#Catalog"#小說的網址 def getdata(url): html=requests.get(url).text # print(html) doc=etree.HTML(html)#構造xpath的決議物件 contents=doc.xpath('//*[@]/li') # print(contents) for content in contents: links=content.xpath('h2/a/@href') for link in links: hurl="https:"+link#小說某一章的網址 html=requests.get(hurl).text#獲取到源代碼 doc=etree.HTML(html)#構造xpath決議物件 title=doc.xpath('//*[@]/div/div[1]/h3/span[1]/text()') content=doc.xpath('//*[@]/p/text()') with open('novel/%s.txt'%title[0],mode='w',encoding='utf-8') as f: for abd in content: f.write(abd) a=getdata(url)
函式功能介紹
學習了entree對網頁原始碼進行決議,requests庫對網頁進行決議獲得原始碼,同時代碼中還用到了獲取標簽xpath的方法,xpath的決議將在下一篇文章進行決議,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/527983.html
標籤:Python
上一篇:【python】都2022年不會還有人不會在電腦桌面上養寵物吧~
下一篇:重溫Python基礎——字串
