天天看点

#Python新征程22#用requests和BeautifulSoup爬取网络小说

作者:梁园燕栖

每天的学习过程都是自我更新和自我提高的过程,将这个过程分享出来是一种乐趣,让更多的人见证我的学习成果,并可能从我的学习成果中获得收益。这样一个人的乐趣就变成了很多人的乐趣。

#Python新征程22#用requests和BeautifulSoup爬取网络小说

今天使用requests 和BeautifulSoup在Pycharm环境中爬取网络小说,参考书中案例,爬取金镛先生的小说。步骤如下:

1、打开网页,F12打开开发者模式,在源代码中找到对应爬取的文本内容,看是否具有唯一性。如果具有唯一性,就可以直接爬取,没有唯一性,呃……后面学习中看看能否找到爬取方案。

#Python新征程22#用requests和BeautifulSoup爬取网络小说

2、在Pycharm环境中调用requests 和BeautifulSoup,编写对应爬取代码(书中196页代码return的缩进有误,调整之后可以运行)

3、点击运行,自动完成爬取,金镛先生的简介就出现在了结果显示框中。

#Python新征程22#用requests和BeautifulSoup爬取网络小说

4、继续修改代码,找到列表名称的上级代码,按图索骥,开始爬取小说列表的内容

5、爬取之后的效果,只是显示了一个小说名称和链接,这又是为什么呢?

#Python新征程22#用requests和BeautifulSoup爬取网络小说

6、完整的代码如下:

'''
eg-1 通过requests 和BeautifulSoup 爬取金镛小说
'''
import requests
from bs4 import BeautifulSoup
def getHTML(url):
    try:
        r=requests.get(url)
        html=r.text
        return html
    except:
        print("error")

def getJinYong(html):
    soup=BeautifulSoup(html,"html.parser")
    target = soup.p.string
    return target
#书中196页,return代码的缩进有误,正常应该缩进到target一样的程度

def getBookURL(html):
    book_url={}
    soup=BeautifulSoup(html,"html.parser")
    target = soup.select(".co3 a")
    book = [item.string for item in target]
    url=[item.attrs["href"] for item in target]
    for item,url in zip(book,url):
        book_url[item]="http://www.wuxia.net.cn/"+url
        return book_url
if __name__=="__main__":
    url = "http://www.wuxia.net.cn/author/jinyong.html"
    html=getHTML(url)
    print("爬取金镛先生简介文本为:", getJinYong(html))
    print("爬取金镛小说及链接地址为:",getBookURL(html))           

#加油!

#一点一滴的努力,未来都会有回报。

#岁月静好,不去羡慕旁人,只做好自己,花朵总会绽放。

#Python新征程22#用requests和BeautifulSoup爬取网络小说

#以上学习感悟来自于《网络爬虫进化论:从Excel爬虫到Python爬虫》(中国水利水电出版社2021年出版)