下面的代码是通过BeautifulSoup解析某个网站的html代码,然后通过特定标签实现爬取该网站上的小说名字和链接。
from bs4 import BeautifulSoup
from urllib import request
if __name__ == '__main__':
target_url = 'http://www.biqukan.com/1_1094/'
req = request.Request(target_url)
response = request.urlopen(req)
response = response.read().decode('gbk')
#print(response)
soup = BeautifulSoup(response,'lxml')#将response用BeautifulSoup按照lxml的格式解析,得到一个BeautifulSoup对象
#并能按照标准的缩进格式的结构输出
#print(soup.prettify()) #结构化输出
#搜索建立的文档树,找出来div标签中class是listmain的所有子标签
chapter = soup.find_all('div', class_ = 'listmain')
#使用查询结果在此创建一个BeautifulSoup对象,继续对其解析
download_soup = BeautifulSoup(str(chapter),'lxml')
print(download_soup.prettify())
flag = False
#遍历dl标签下的所有子节点 children只包含直接子节点
for child in download_soup.dl.children:
#过滤掉回车,(这个地方为什么会有空行暂时不太理解,回头再研究)
if child !='\n':
if child.string == '《一念永恒》正文卷':
flag = True
if flag == True and child.a != None:
download_url = "http://www.biqukan.com" + child.a.get('href')
download_name = child.string
print(download_name, ': ',download_url)
# for b in soup.find_all('a'):
#print(b['href'],b.string)
#print(soup.find_all('a'))