本文是《Web scraping with python》的简单的学习笔记,默认在python 3.0版本上运行,所以在运行时使用python3 name.py命令。
第一章 第一个网络爬虫
本章给出一个简单的web 爬虫代码段如下:
from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
def getTitle(url):
try:
html = urlopen(url)
except HTTPError as e:
return None
try:
bsObj = BeautifulSoup(html.read())
title = bsObj.body.h1
except AttributeError as e:
return None
return title
title = getTitle("http://www.pythonscraping.com/pages/page1.html")
if title == None:
print("Title could not be found")
else:
print(title)
定义了一个getTitle方法来获取网页的标题,其中有简单的处理异常机制。在网页爬虫的编写过程中,异常是非常常见的,所以需要处理异常。简单的总结本章的爬虫,第一步urlopen一个网页,然后将这个网页的内容(. read())转化成BeautifulSoup对象,从而提取该对象中的各种标签内容。
第二章 HTML网页解析
BeautifulSoup包中有两个重要的方法:find()(找第一个)和findAll()(找所有)。它们可以有很多参数,但是绝大多数情况下只需要使用两个就行了。
find(tag,attributes)和 findAll(tag,attributes)
例如
nameList = bsObj.findAll("span", {"class":"green"})
nameList = bsObj.find("span", {"class":"green"})
即获得span标签下,属性class为green的内容。当然我们还可以同时获得class为red的内容,代码如下
nameList = bsObj.findAll("span", {"class":"green","class":"red"})
nameList = bsObj.find("span", {"class":"green","class":"red"})
&nbs