工具:python3.6  pycharm

库:bs4 + urllib

第一步:读取html源码

from bs4 import BeautifulSoup
import urllib.request#导入urllib库
url = 'https://www.p y t hontab.com/html/pythonhexinbiancheng/index.html'#获取网页链接
request = urllib.request.urlopen(url)
html = request.read()#读取网页源代码

第二步:获取内容和标题

soup = BeautifulSoup(html,'html.parser')#解析html
title_links = soup.select('#catlist > li > a')#找到标题与链接
source_list = []#存储标题与链接的字典
for title_link in title_links:
data = {
'title' : title_link.get_text(),
'link' : title_link.get('href')
}
source_list.append(data)

第三步:在当前目录下新建一个lesson的文件夹,将文件存储在此文件夹下

for dic in source_list:#遍历每一个字典
request = urllib.request.urlopen(dic["link"])
html = request.read()
soup = BeautifulSoup(html, 'html.parser')
text_p = soup.select('#Article > div.content > p')#拿到p标签下的数据
text = []#存储文章内容
for a in text_p:
text.append(a.get_text().encode('utf-8'))#取出p标签下的文本部分,即文章的内容
name = dic["title"]
with open('lesson/%s.txt' % name, 'wb') as f:#将文章写入文件
for line in text:
f.write(line)

数据爬取完毕。

注:以上完成一个页面的抓取,若想多抓取页面的话,可用以下代码:

from bs4 import BeautifulSoup
import urllib.request#导入urllib库
url_list = ['https://www.p y t hontab.com/html/pythonhexinbiancheng/index.html']#获取网页链接
for i in range(2,20):
url = 'https://www.py tho ntab.com/html/pythonhexinbiancheng/%s.html' % i
url_list.append(url)
for url in url_list:
request = urllib.request.urlopen(url)
html = request.read()#读取网页源代码
soup = BeautifulSoup(html,'html.parser')#解析html
title_links = soup.select('#catlist > li > a')#找到标题与链接
source_list = []#存储标题与链接的字典
for title_link in title_links:
data = {
'title' : title_link.get_text(),
'link' : title_link.get('href')
}
source_list.append(data) for dic in source_list:#遍历每一个字典
request = urllib.request.urlopen(dic["link"])
html = request.read()
soup = BeautifulSoup(html, 'html.parser')
text_p = soup.select('#Article > div.content > p')#拿到p标签下的数据
text = []#存储文章内容
for a in text_p:
text.append(a.get_text().encode('utf-8'))#取出p标签下的文本部分,即文章的内容
name = dic["title"]
directory = '%s.txt' % name
dir = directory.replace('/','_').replace('*','@').replace('"','o').replace('?','w').replace(':','m')
with open('lesson/'+dir, 'wb') as f:#将文章写入文件
for line in text:
f.write(line)

最新文章

  1. 最近碰到的一些 SSL 问题记录
  2. Spring 3种注入方式
  3. 实战SQL注入
  4. js-设置焦点
  5. tomcat 启用Gzip 压缩进行优化
  6. 理解MapReduce哲学
  7. PerformSelector may cause a leak because its selector is unknown 解决方法
  8. UVA10817--状态压缩DP
  9. MFC串口通信
  10. JQuery中根据表单元素动态拼接json 字符串
  11. java自带uuid生成
  12. myeclipse db browser 新建数据源
  13. php用PHPWord库生成word文档的例子
  14. python中__str__与__repr__的区别
  15. git - 管理项目(SourceTree的使用)
  16. 剑指offer(17)树的子结构
  17. Jmeter处理返回结果的值
  18. bzoj 4084 双旋转字符串
  19. mysql取以当前时间为中心的任意时间段的时间戳
  20. UVa 10537 The Toll! Revisited (最短路)

热门文章

  1. C#中List<T>排序
  2. git 提交顺序
  3. linux 查看路由表
  4. Lodop提示安装或升级的注意事项
  5. Running Web API using Docker and Kubernetes
  6. 【数学建模】day07-数理统计II
  7. BZOJ3438小M的作物——最小割
  8. springboot 学习
  9. 初步了解HTML
  10. Codeforces555 B. Case of Fugitive