python3爬取小说_python3下BeautifulSoup练习一(爬取小说)

from bs4 import BeautifulSoup

import urllib.request

import re

import os,time

def getUrls(url):

urls = []

#url = 'http://www.ahzww.net/0/178/'

req = urllib.request.Request(url)

page = urllib.request.urlopen(req)

html = page.read()

soup = BeautifulSoup(html,'html.parser')

i = 0

for k in soup.find_all(href=re.compile('.html')):

#print('www.qu.la'+k['href'],k.get_text())

if i != 0:

urls.append('http://www.ahzww.net'+k['href'])

i = i+1

return urls

def getContent(url):

#url = 'http://www.ahzww.net/0/178/355185.html'

headers = ('User-Agent','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11')

opener = urllib.request.build_opener()

opener.addheaders = [headers]

html = opener.open(url).read()

soup = BeautifulSoup(html,'html.parser')

content = soup.find('div',id='content')

title = soup.find('h1')

return title.get_text(),content.get_text()

if __name__ == '__main__':

urls = getUrls('http://www.ahzww.net/0/178/')

#print(urls)

fp = open("不负娇宠.txt","w")

for url in urls:

print(url)

title,content = getContent(url)

fp.write(title+"\n")

fp.write(content.replace('        ','\n')+"\n")

time.sleep(2)

fp.close()

print("Done")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值