[TOC]
目标
用scrapy写一个可以下载页面,解析静态页面的爬虫,加head,加链接生成器
解析,可能用xpath+bs
安装
conda install scrapy
如果已经安装过,要升级,执行
conda update scrapy
生成原始爬虫
新建一个文件夹scrapy,然后执行scrapy startproject tutorial
,生成demo
在tutorial/spider目录下,新建dmoz_spider.py,输入下面代码
#!/usr/bin/python
# -*- coding: utf-8 -*-
# __author__ = "leisurem"
import sys
import scrapy
from bs4 import BeautifulSoup
reload(sys)
sys.setdefaultencoding('utf-8')
class DmozSpider(scrapy.spiders.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
'http://jobs.51job.com/nanjing/76840759.html?s=0',
]
def parse(self, response):
# print response.url.split("/")
filename = response.url.split("/")[-1]
with open(filename, 'wb') as f:
soup = BeautifulSoup(response.body, "html5lib")
company_name = soup.find('p', class_="cname").get_text().strip()
job_title = soup.find('h1').get('title')
job_describe = soup.find(
'div', class_="bmsg job_msg inbox").get_text().split()[1]
company_address = soup.find(
'div', class_="bmsg inbox").get_text().split()[0]
company_info = soup.find(
'div', class_="tmsg inbox").get_text().split()[0]
f.write('company_name is ' + company_name + '\n' + '\n')
f.write('job_title is ' + job_title + '\n' + '\n')
f.write('job_describe is ' + job_describe + '\n' + '\n')
f.write('company_address is ' + company_address + '\n' + '\n')
f.write('company_info is ' + company_info + '\n' + '\n')
bs4
这边的解析用了BeautifulSoup
简要介绍一下bs4的用法
bs4是和xpat不太一样的一种路径定位方式(当然,你实在需要,bs也支持re定位)
安装
conda install beautifulsoup4
conda install html5lib
conda install lxml
bs解析
bs里面的东西多,介绍几种方法
标签定位
如果已经知道要定位的内容在a标签内,但是a标签往往不止一个,可以数一下再第几个a标签内,比如再第6个a标签里soup.find_all('a')[5].get_text()
如果,知道就是第一个a标签,则可以用soup.find('a').get_text()
正则
找出所有b开头的标签,比如body,b,b2这些都会被找出来
import re
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
下面代码找出所有名字中包含”t”的标签
for tag in soup.find_all(re.compile("t")):
print(tag.name)
- 类解析
如果是类似这样的代码,可以按照类名和值搜索tag
<p class="cname">
<a href="http://jobs.51job.com/all/co268532.html" target="_blank" title="万得信息技术股份有限公司(Wind资讯)">万得信息技术股份有限公司(Wind资讯)<em class="icon_b i_link"></em></a>
</p>
soup.find('p', class_="cname").get_text().strip()
加配置头
打开firefox,按f12,点reload
按钮,然后点旁边的edit and resent
,拷贝head
打开项目目录下的settings.py,输入下面代码
DEFAULT_REQUEST_HEADERS = {
'Host': 'jobs.51job.com',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'zh-CN,en-US;q=0.7,en;q=0.3',
'Accept-Encoding': 'gzip, deflate',
'Cookie': 'guid=14676224113529970042; ps=us%3DWmZSMFUpBzYAZg99VzBXZw09U3wANAdmBTBVe1tgAjYPMVo5VDEDNlM3CGALZ1NpBD4BNAE1VXxWFQA4AHAEcVpg%26%7C%26nv_3%3D; 51job=cuid%3D67028249%26%7C%26to%3DDTMCblc1VGAAaQxiB2ZRawN8BWgHZFVpUidWcQtzUjcBZAUiBWZTYFc2WjYKbV1pAzFXYwQxB2M%253D%26%7C%26cusername%3Dleisurem%26%7C%26cpassword%3D%26%7C%26ccry%3D.02PaxjLxs3vQ%26%7C%26cresumeid%3D88438738%26%7C%26cresumeids%3D.0RBx5M27b7UU%257C%26%7C%26cname%3D%25C2%25ED%25CE%25C4%25BD%25DC%26%7C%26cemail%3Dleisurem%2540126.com%26%7C%26cemailstatus%3D3%26%7C%26cnickname%3D%26%7C%26cenglish%3D0%26%7C%26cautologin%3D1%26%7C%26sex%3D0%26%7C%26cconfirmkey%3DleDLv4rER1zlU%26%7C%26cnamekey%3DleVc9stx.CGiQ; slife=lastvisit%3D070200; search=jobarea%7E%60070200%7C%21ord_field%7E%600%7C%21recentSearch0%7E%601%A1%FB%A1%FA070200%2C00%A1%FB%A1%FA000000%A1%FB%A1%FA0000%A1%FB%A1%FA00%A1%FB%A1%FA9%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA%C4%A3%D0%CD+++%BB%D8%B2%E2%A1%FB%A1%FA2%A1%FB%A1%FA%A1%FB%A1%FA-1%A1%FB%A1%FA1469523105%A1%FB%A1%FA0%A1%FB%A1%FA%A1%FB%A1%FA%7C%21recentSearch1%7E%601%A1%FB%A1%FA070200%2C00%A1%FB%A1%FA000000%A1%FB%A1%FA0000%A1%FB%A1%FA00%A1%FB%A1%FA9%A1%FB%A1%FA99%A1%FB%A1%FA07%2C08%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA07%2C06%2C05%2C04%2C03%A1%FB%A1%FApython++++%B9%C9%C6%B1%A1%FB%A1%FA2%A1%FB%A1%FA%A1%FB%A1%FA-1%A1%FB%A1%FA1469518712%A1%FB%A1%FA0%A1%FB%A1%FA%A1%FB%A1%FA%7C%21recentSearch2%7E%601%A1%FB%A1%FA070200%2C00%A1%FB%A1%FA000000%A1%FB%A1%FA0000%A1%FB%A1%FA00%A1%FB%A1%FA9%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA07%2C06%2C05%2C04%2C03%A1%FB%A1%FApython++++%B9%C9%C6%B1%A1%FB%A1%FA2%A1%FB%A1%FA%A1%FB%A1%FA-1%A1%FB%A1%FA1469518699%A1%FB%A1%FA0%A1%FB%A1%FA%A1%FB%A1%FA%7C%21recentSearch3%7E%601%A1%FB%A1%FA070200%2C00%A1%FB%A1%FA000000%A1%FB%A1%FA0000%A1%FB%A1%FA00%A1%FB%A1%FA9%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FApython++++%B9%C9%C6%B1%A1%FB%A1%FA2%A1%FB%A1%FA%A1%FB%A1%FA-1%A1%FB%A1%FA1469518681%A1%FB%A1%FA0%A1%FB%A1%FA%A1%FB%A1%FA%7C%21recentSearch4%7E%601%A1%FB%A1%FA070200%2C00%A1%FB%A1%FA000000%A1%FB%A1%FA0000%A1%FB%A1%FA00%A1%FB%A1%FA9%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FApython++%C1%BF%BB%AF%A1%FB%A1%FA2%A1%FB%A1%FA%A1%FB%A1%FA-1%A1%FB%A1%FA1469518666%A1%FB%A1%FA0%A1%FB%A1%FA%A1%FB%A1%FA%7C%21collapse_expansion%7E%601%7C%21; nsearch=jobarea%3D%26%7C%26ord_field%3D%26%7C%26recentSearch0%3D%26%7C%26recentSearch1%3D%26%7C%26recentSearch2%3D%26%7C%26recentSearch3%3D%26%7C%26recentSearch4%3D%26%7C%26collapse_expansion%3D',
'Connection': 'keep-alive',
'Cache-Control': 'max-age=0',
}
定义item
打开items.py,加入以下代码来定义抓取域,暂定五个,包括工资,职位,职位描述,公司类型,公司规模,公司行业
job_pay = Field()
job_title = Field()
job_describe = Field()
company_type = Field()
company_scale = Field()
company_industry = Field()
url抽取器
考虑到url抽取略慢,重写了url抽取器
在tutorial下新建buildlink.py,完成url抽取器的编码
主要思路是先解析出所在地区的url样式,以及当天本地区更新的职位数量,然后直接生成,而非按页解析出每个职位列表页的链接
如http://search.51job.com/list/070200,070211,0000,00,9,99,%2B,2,1.html
是某地的一个职位列表页,通过分析程序可以在这边页面上解析出当前总共的职位列表有多少页,然后替换最后的数字1来生成本地区的所有职位列表的url
运行爬虫
把url抽取器加入到spider之后,即可运行爬虫,输出格式为json,下面是修改后的代码
class DmozSpider(scrapy.spiders.Spider):
name = "51job"
def __init__(self):
self.allowed_domains = ["51job.com"]
self.start_urls = ['http://jobs.51job.com/nanjing-xwq/77959226.html?s=0', ]
def parse(self, response):
item = TutorialItem()
soup = BeautifulSoup(response.body, "html5lib")
item['job_title'] = soup.find('h1').get('title')
item['job_pay'] = soup.find('div', class_="cn").strong.get_text().strip()
item['job_describe'] = soup.find('div', class_="bmsg job_msg inbox").get_text().split()[1]
item['company_type'], item['company_scale'], item['company_industry'] = [x.strip() for x in soup.find('p', class_="msg ltype").get_text().split('|')]
yield item
运行命令如下
scrapy crawl 51job -o items.json
后续工作
根据爬虫设计概要,下面会运行一段时间,这期间不可避免的会遇到一些问题:
- 登陆,获取cookie
- 登陆又会遇到验证码的问题\
- 对于打算抓取的页面,需要进行url去重,这可能会涉及bloomfilter
- 对于打算解析的页面,可能会涉及页面重复的判断
- 数据存储会进一步优化
- 图片存储会加进来
- 同时考虑js解析的问题