Python 爬虫从入门到进阶之路(十三)

之前的文章我们介绍了一下 BeautifulSoup4 模块,接下来我们就利用 BeautifulSoup4 模块爬取《糗事百科》的糗事。

之前我们已经分别利用 re 模块和 Xpath 模块爬取过糗百,我们只需要在其基础上做一些修改就可以了,为了保证项目的完整性,我们重新再来一遍。

我们要爬取的网站链接是 https://www.qiushibaike.com/text/page/1/ 。

Python 爬虫从入门到进阶之路(十三)

我们通过浏览器开发者工具的控制台发现我们想要的数据在  <div class="content">......</div>  内:

Python 爬虫从入门到进阶之路(十三)

根据上面的分析我们可以写出代码如下:

1 import urllib.request 2 from bs4 import BeautifulSoup 3 import ssl 4 5 # 取消代理验证 6 ssl._create_default_https_context = ssl._create_unverified_context 7 8 9 url = "https://www.qiushibaike.com/text/page/1/" 10 # User-Agent头 11 user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36' 12 headers = {'User-Agent': user_agent} 13 req = urllib.request.Request(url, headers=headers) 14 response = urllib.request.urlopen(req) 15 # 获取每页的HTML源码字符串 16 html = response.read().decode('utf-8') 17 # 解析html 为 Beautiful Soup 对象 18 soup = BeautifulSoup(html, "lxml") 19 content_list = soup.select('div.content') 20 print(content_list)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgffds.html