声明:爬虫为学习使用,请各位同学务必不要对当放网站或i服务器造成伤害。务必不要写死循环。
-
练习目标:爬取https://b.faloo.com/BuyBook.aspx?id=526024 《我的高中女友门》
-
解释请看代码注释:
主要是网页是xxx/1.html,xxx/2.html这种数字递增的网页;小说内容在id=content这个地方。
from bs4 import BeautifulSoup
import urllib.request
def down(url, num):
# 获取网页
response = urllib.request.urlopen(url)
html = response.read().decode('gbk') # 编码格式gb2312,utf-8,GBK
html_string = str(html) # 转换成string,可以直接向数据库添加
soup = BeautifulSoup(html_string, "html.parser") # 解析网页标签
try:
# 匹配抓取区域
# pid = soup.find(attrs={"id": "content"})
pid = str(soup.findAll('div', {"id": "content"})[0])
print("当前页数=" + str(num))
print(type(pid))
# 将抓取区域保存至txt文件
fh = open('我的高中女友们.txt', 'a', encoding='utf-8') # 制定txt编码,避免中文编码解析报错。a可以持