之前实现python的网络爬虫, 主要都是使用较为底层的urllib, urllib2 实现的, 这种实现方案显得比较原始, 编码起来也比较费劲, 尤其是提取信息的时候, 还得使用正则表达是匹配 (之前转载的一篇糗事百科的爬虫文章, http://blog.csdn.net/zhyh1435589631/article/details/51296734)。 我们这里采用requests + beautifulsoup 的实现方案, 使用 css 选择器, 简化代码的书写。
代码比较简洁, 就不多说了, 下面的代码中, 我们分别爬取两个网站, 糗事百科 和 我们学校的就业网站。
# -*- coding=utf8 -*-
import requests
from bs4 import BeautifulSoup
def qiushibaike():
content = requests.get('http://www.qiushibaike.com').content
soup = BeautifulSoup(content, 'html.parser')
for div in soup.find_all('div', {'class' : 'content'}):
print div.text.strip()
def ustcjob():
headers = {'User-Agent':'Mozilla / 5.0(X11;Linux x86_64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 50.0.2661.102 Safari / 537.36'}
content = requests.get('http://job.ustc.edu.cn/list.php?MenuID=002', headers = headers).content
soup = BeautifulSoup(content, 'html.parser')
for Jop in soup.find_all('div', {'class' : 'Joplistone'}):
for item in Jop.find_all('li'):
print "%-30s%-20s%-40s" % (item.a.text.strip() , item.span.text.strip() , item.span.next_sibling.text.strip())
if __name__ == '__main__':
#qiushibaike()
ustcjob()