資源簡介
自己練手的代碼,爬蟲小程序,爬一些鬼故事。。。自己練手的代碼,爬蟲小程序,爬一些鬼故事。。。自己練手的代碼,爬蟲小程序,爬一些鬼故事。。。自己練手的代碼,爬蟲小程序,爬一些鬼故事。。。
代碼片段和文件信息
import?requests
from?lxml?import?etree
import?pymysql
import?time
class?kunbubooks(object):
????def?__init__(self):
????????#?self.URL?=?“http://www.bestgushi.com/o/kongbu/index.html“
????????self.headers?=?{‘User-Agent‘:‘Mozilla/4.0?(compatible;?MSIE?8.0;?Windows?NT?6.1;?WOW64;?Trident/4.0;?SLCC2;?.NET?CLR?2.0.50727;?.NET?CLR?3.5.30729;?.NET?CLR?3.0.30729;?Media?Center?PC?6.0;?.NET4.0C;?InfoPath.3)‘}
????????#?創建數據庫連接對象與游標對象
????????#?self.db?=?pymysql.connect(‘localhost‘
????????#?????????????????????????????‘root‘
????????#?????????????????????????????‘123456‘
????????#?????????????????????????????‘gushi‘
????????#?????????????????????????????charset=‘utf8‘)
????????#?self.cursor?=?self.db.cursor()
????def?bookurllist(selfURL):
????????#?請求三步
????????res?=?requests.get(URLheaders=self.headers)
????????res.encoding?=?‘gbk‘
????????html?=?res.text
????????parseHtml?=?etree.HTML(html)
????????#?找出一頁中所有故事的鏈接
????????books?=?parseHtml.xpath(“//div[@class=‘gs‘]/h3/a/@href|//div[@class=‘gs?yt‘]/h3/a/@href“)
????????for?b?in?books:
????????????self.book(b)???#循環遍歷每個故事鏈接,調用并交給book函數
????def?book(selfb):
????????res?=?requests.get(bheaders=self.headers)
????????res.encoding?=?‘gbk‘??#文中有些是gb2312解不出來的,所以要用到gbk
????????html?=?res.text
????????parseHtml?=?etree.HTML(html)?
????????book?=?parseHtml.xpath(“//div[@id=‘zzzxcwqsdas‘]//p//text()“)?#得到故事內容列表
????????bookname?=?parseHtml.xpath(“//div[@class=‘gushi‘]/h1/a/text()“)??#得到故事名
????????
????????for?x?in?range(250):
????????????y?=?b[:-5]?+?‘_‘?+?str(x)?+?‘.html‘?#拼接每個故事頁面中的分頁鏈接
????????????#?循環請求分頁鏈接?
????????????res1?=?requests
評論
共有 條評論