python爬虫初体验
文章目录
第一次写python爬虫,用的是Beautifulsoup库,实现了简单网页的内容爬取。
1.首先是beautifulsoup的安装:
pip install beautifulsoup
2.Beautifulsoup库最常用的对象是Beautifulsoup对象,我写了一个简单的例子:
from urllib import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page1.html")
bsObj = BeautifulSoup(html.read())
print(bsObj.h1)
要注意的是有的教材第一行代码是这样写的:
from urllib import urlopen
但是这样运行的时候是会报错的,到网上查了之后发现Python urllib中没有request 这个模块,只需要将request去掉即可。
运行的结果为

3.根据css层叠样式表选择爬取:
from urllib import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/warandpeace.html")
bs0bj = BeautifulSoup(html,"lxml")
nameList = bs0bj.findAll("span",{"class":"green"})
for name in nameList:
print(name.get_text())
通过findAll()函数抽取只包含在 标签里的文字,这样就会得到一个人物名称的 Python 列表。这样就可以对网页内容进行有选择的选取。下面还有子标签.children,兄弟标签用next_siblings()函数,父标签previous_siblings()函数.通过这些函数就能对网页信息进行有效的删选。
注:get_text() 会把你正在处理的 HTML 文档中所有的标签都清除,然后返回
一个只包含文字的字符串.
文章作者 Xujunhao
上次更新 2017-02-28