python——笔趣网小说爬取
今天小编学习了爬取笔趣网小说,觉得很有意思(以前爬取起点没成功????,难受),今天终于成功了,特来分享一下。
今天采用的库有: requests, bs4中的BeautifulSoup
requests:用于获取网络请求,拿到网站的html数据
BeautifulSoup:是一个网页选择器,解析html或者tml,提取想要的数据(虽然是解析库,但是也要html解析库进行解析)
import requests
from bs4 import BeautifulSoup
import os
请求网站,拿到网站的html数据
response = requests.get(‘http://www.biquw.com/book/94/’).text
#运用html解析库解析
soup = BeautifulSoup(response, ‘lxml’)
#拿到小说的链接
data_list = soup.find(‘ul’)
#print(data_list) # 打印ul标签下的东西
#下面要获取小说章链接,章名
小编用了list方式,进行遍历
for item in list(data_list.find_all(‘a’)):
# print(’{}:{}’.format(item.text, “http://www.biquw.com/book/94/” + item[‘href’]))
book_url = “http://www.biquw.com/book/94/” + item[‘href’]
book = requests.get(book_url).text
book_soup = BeautifulSoup(book, ‘lxml’)
content = book_soup.find(‘div’, {‘id’: ‘htmlContent’}).text
if not os.path.exists(“剑道独尊.txt”):
os.mkdir(“剑道独尊.txt”)
filename = “剑道独尊.txt” + “\” + item.text + “.txt”
with open(filename, “a”, encoding=“utf-8”) as f:
f.write(content)
上图就是结果,愿对你们有帮助??????