众所周知python是一门比较适合用来开发爬虫的语言,因为python有很多爬虫库,比较常用的库如:requests,Selenium,l ,Beautiful Soup,pyquery等等.
下面我就简单介绍一下用requests+Beautiful Soup来做实验.
首先找到一个要采集的网址,我这里采集是以: kan1234.com/post/34.html为例
首先用chorme打开这个网址,然后同时按下键盘Ctrl+U键,在查看源代码页面定位到标题,如下图

可以了解到标题的标签是<h1>,那么我们就可通过Beautiful Soup解析库输入:
bs.find("h1").getText() #获取标题
去获取标题.
我们再定位到内容如下图:

可以了解到内容的标签是<div class="newstext typo typo-selection">,那么我们就可通过Beautiful Soup解析库输入:
content = bs.find(div",class_="newstext")
详细代码如下:
# coding=utf-8 #设置页码编码,解决中文乱码
import requests
from bs4 import BeautifulSoup
header = {
'User-Agent': 'Mozilla/5.0 (compatible; Baiduspider/2.0; +)' #模拟Baiduspider抓取
}
url = '抓取的URL
respose = requests.get(url,headers=header,timeout=6) #, timeout超时时间
respose.encoding='utf-8' #设置网页编码
html = respose.text #获取html内容
bs = BeautifulSoup(html,"html.parser") #指定Beautiful的解析器为“html.parser
title = bs.find("h1").getText() #获取标题
content = bs.find("div",class_="newstext") #获取内容
print('标题:%s' %title)
print('内容:\n%s' %content)
最后运行结果如下图:

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/26261504/viewspace-2777657/ ,如需转载,请注明出处,否则将追究法律责任。