任务预览(两天)
2.1 学习beautifulsoup
1.学习beautifulsoup,并使用beautifulsoup提取内容。
2.使用beautifulsoup提取丁香园论坛的回复内容。
注:丁香园直通点:http://www.dxy.cn/bbs/thread/626626#626626 。
2.2学习xpath
1.学习xpath,使用lxml+xpath提取内容。
2.使用xpath提取丁香园论坛的回复内容。
注丁香园直通点:http://www.dxy.cn/bbs/thread/626626#626626 。
2.1.1学习beautifulsoup,并使用beautifulsoup提取内容。
BeautifulSoup简介:
BeautifulSoup提供一些简单的、Python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。 BeautifulSoup 自动将输入文档转换为 Unicode 编码,输出文档转换为 utf-8 编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时你仅仅需要说明一下原始编码方式就可以了。 BeautifulSoup 已成为和 lxml、html6lib 一样出色的 Python 解释器,为用户灵活地提供不同的解析策略或强劲的速度。
导入beautifulsoup的库:
from bs4 import BeautifulSoup
2.1.2使用beautifulsoup提取丁香园论坛的回复内容。
从规律上,不难看出,所有评论都是在<td class=“postbody”>中。我们可以通过筛选全部的class="postbody"来获得评论。
from bs4 import BeautifulSoup
import requests
#利用requests抓取网页
def get_html(url):
HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 ''(KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
response = requests.get(url, headers=HEADERS)
response.encoding = 'utf-8'
if response.status_code == 200:
return response.text
return None
#通过BeautifulSoup筛选出评论
def get_info(html):
soup = BeautifulSoup(html, 'lxml')
return soup.find_all(attrs={'class': 'postbody'})
#主体
if __name__ == '__main__':
url = "http://www.dxy.cn/bbs/thread/626626#626626"
html = get_html(url)
infos = get_info(html)
for i in range(len(infos)):
print('-'*100)
print(infos[i].text.strip()) #利用strip()将获取的文本前后的空格删去,只留下文本
结果
2.2.1学习xpath,使用lxml+postbody提取内容。
XPath(XML Path Language),即 XML 路径语言,它是一门在XML文档中查找信息的语言。XPath 最初设计是用来搜寻XML文档的,但是它同样适用于 HTML 文档的搜索。所以在做爬虫时,我们完全可以使用 XPath 来做相应的信息抽取。
XPath常用规则:
表达式 | 描述 |
---|---|
nodename | 选取此节点的所有子节点 |
/ | 从当前节点选取直接子节点 |
// | 从当前节点选取子孙节点 |
. | 选取当前节点 |
… | 选取当前节点的父节点 |
@ | 选取属性 |
导入与xpath有关的库:
from lxml import etree
2.2.2使用xpath提取丁香园论坛的回复内容。
原理同上
from lxml import etree
import requests
#利用requests抓取网页
def get_html(url):
HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 ''(KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
response = requests.get(url, headers=HEADERS)
response.encoding = 'utf-8'
if response.status_code == 200:
return response.text
return None
#通过Xpath筛选出评论
def get_info(html):
info_html = etree.HTML(html)
result = info_html.xpath('//td[@class="postbody"]//text()')
return result
#主体
if __name__ == '__main__':
url = "http://www.dxy.cn/bbs/thread/626626#626626"
html = get_html(url)
infos = get_info(html)
for i in range(len(infos)):
print(infos[i].strip()) #利用strip()将获取的文本前后的空格删去,只留下文本