BeautifulSoup + requests 爬虫
概述
本例不涉及cookie,即抓取的资源无需登录认证。爬虫主要做两件事,一个是抓取请求链接,另一个是分析响应的数据。鉴于扇贝单词书的词串页中的页码是通过js动态生成,直接抓取页面内容是不能获取,因此程序模拟了它的分页请求路径
分析
- 向目标url发请求,拉取响应体
- 分析页面 爬取指定内容 抓取链接 分析数据
- 数据写入文件输出,需要注意写入编码,若未指定
py
会采用操作系统的默认编码 BeautifulSoup
解析单词书页 --> 词串页 ,分别拉取章节目录,词串页目录各自链接
源码
getSoup
用bs4
抓取目标url页内容,返回一个soup
对象getChapterLinks
getWordLinks
先提取章节的入口链接,后提取第该章每一页的链接getWords
真正获取目标数据,随后持久化
from bs4 import BeautifulSoup
import requests
import math
baseurl = 'https://www.shanbay.com'
pyBookUrl = 'https://www.shanbay.com/wordbook/187711/'
def getSoup(url):
rsp = requests.get(url)
if rsp.status_code == 200:
return BeautifulSoup(rsp.content, "lxml")
return None
def getChapterLinks(pyBookUrl):
chapters = getSoup(pyBookUrl).select('td.wordbook-wordlist-name > a')
return [(chapter.get_text(), chapter['href']) for chapter in chapters]
def getWordLinks(startUrl):
entryUrl = '%s%s' % (baseurl, startUrl)
numVocab = getSoup(entryUrl).find('span', {'id': 'wordlist-num-vocab'}).get_text()
pages = math.ceil(int(numVocab)/20)
return [(page, '%s?page=%d' % (entryUrl, page))for page in range(1, pages+1)]
def getWords(wordPage):
wordList = getSoup(wordPage).select('td.span2 > strong')
return [" "+word.get_text() for word in wordList]
with open("pyWord.txt", "w", encoding="utf8") as f:
for chapter, chapterLink in getChapterLinks(pyBookUrl):
f.write(chapter+"\n")
for page, link in getWordLinks(chapterLink):
f.write('第%d页' % page)
f.writelines(getWords(link))
f.write('\n')
f.write('\n')
小结
- 本例更多的是分析页面结构,
bs
一些使用技巧
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: