今日份........

本來是想爬小說,並把內容下載到本地。。。

結果看了半天的網頁,分析源代碼。。。

依然沒得頭緒。。。

還是自己太菜了。。。

於是。。。

於是,只能爬個封面圖片,還有簡介咯。。。


#爬取起點網站小說信息#

#小說名#作者#簡介#封面圖片#

import requests

from lxml import etree

#定義爬取的最大頁數#

MAX_PAGE=50

#獲取信息#

def get_page(url):

headers={User-Agent:Mozilla/5.0(Macintosh; Intel Mac OS X 10_11_4)AppleWebkit/537.36(KHTML,like Gecko)Chrome/52.0.2743.116 Safari/537.36}

html = requests.get(url,headers=headers)

content=etree.HTML(html.text)

title=content.xpath(//h4//a[@target="_blank"]/text())

author=content.xpath(//*[@class="name"]/text())

type=content.xpath(//*[@class="go-sub-type"]/text())

state=content.xpath(//*[@class="author"]//span/text())

ntroduct = content.xpath(//*[@class="intro"]/text())

src = content.xpath(//*[@class="book-img-box"]//a//img/@src)

intr = parse_intr(introduct)

get_last(title,author,type,state,intr)

save_img(title,src)

#圖片是以二進位形式保存的#這裡通過content()方法來實現

def get_img(src):

for i in range(len(src)):

s=requests.get(https:+src[i])

src[i]=s.content

return src

#小說的簡介中含有空格字元,通過定義下面方法去掉空格字元

def parse_intr(introduct):

for i in range(len(introduct)):

introduct[i]=introduct[i].replace( ,)

return introduct

#轉化為字典形式

def get_last(title,author,type,state,intr):

for i in range(len(title)):

novel={}

novel[title]=title[i]

novel[author]=author[i]

novel[type]=type[i]

novel[state]=state[i]

novel[intr]=intr[i]

save_file(novel)

#保存圖片

def save_img(title,src):

img=get_img(src)

for i in range(len(img)):

#print(正在下載:{}.format(title[i]))

with open(D:Program Filespythonmypythondocument小說 + title[i]+.jpg,wb) as f:

f.write(img[i])

f.close()

#保存文本

def save_file(novel):

print(正在下載:{}.format(novel[title]))

for item in novel:

with open(D:Program Filespythonmypythondocument小說 +novel[title] +.txt,a,encoding=utf-8) as f:

f.write(item+
+novel[item]+
)

f.close()

#遍歷每一頁#運行過程中可能出現異常

#比如local variable f referenced before assignment

#該方法里通過異常處理:出現異常時,重新執行,直到獲取到信息

def main(MAX_PAGE):

base_url=免費作品_起點中文網

for page in range(1,MAX_PAGE+1):

try:

print(正在載入第{}頁.format(page))

get_page(base_url+str(page))

except:

while True:

try:

print(重新正在載入第{}頁.format(page))

get_page(base_url+str(page))

break

except:

continue

continue

print(下載完畢)

main(MAX_PAGE)


代碼不是很簡潔,下載速度也不是很快。。。

嗯,就當熟悉一下xpath的用法,自定義函數,還有爬網頁的一般流程。當寫入的內容是字典形式的時候,可以用for語句遍歷字典,然後依次把字典中的內容寫入。


推薦閱讀:
相关文章