最近一直在学习爬虫,现在已经学习了requests、json、lxml三个模块的内容,复习了正则表达式语法新学习了XPath语法,今天就以职友网上的计算机类招聘信息为例,综合运用自己所学习的知识进行一次简单的爬虫工作。
程序步骤为:输入全国—计算机软件等关键词进入第一页https://www.jobui.com/jobs?cityKw=%E5%85%A8%E5%9B%BD&industry=%E8%AE%A1%E7%AE%97%E6%9C%BA%E8%BD%AF%E4%BB%B6&jobKw=&n=1,通过查看第二页、第三页信息发现地址信息改变的只有最后面的n,由此可以建立url列表,然后遍历url列表发送get请求获取响应,再使用XPath从字符串中获得想要的信息放入content列表,将列表中的信息保存到zhaopin.txt中。在本次实战中我只爬取了岗位名称和对应的url地址。
import requests
import json
from lxml import etree
class ZhaopinSpider:
def __init__(self):
self.start_url = "https://www.jobui.com/jobs?cityKw=%E5%85%A8%E5%9B%BD&industry=%E8%AE%A1%E7%AE%97%E6%9C%BA%E8%BD%AF%E4%BB%B6&jobKw=&n={}"
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"}
def get_url_list(self):#获得下一页地址列表
return [self.start_url.format(i) for i in range(1,68)]
def parse_url(self, url): # 发送请求获取响应
response = requests.get(url, headers=self.headers)
return response.content.decode()
def get_content_list(self, html_str): # 提取数据
html = etree.HTML(html_str)
div_list = html.xpath("//div[@class='fr searchTitTxt']/div[@class='cfix']") # 根据div分组
content_list = []
for div in div_list:
item = {}
item["href"] = ("https://www.jobui.com"+div.xpath("./a[@rel='nofollow']/@href")[0]) if len(div.xpath("./a[@rel='nofollow']/@href")) > 0 else None
item["job"] = div.xpath("./a/h3/text()")[0] if len(div.xpath("./a/h3/text()")) > 0 else None
content_list.append(item)
return content_list
def save_content_list(self, content_list): # 保存数据
with open("zhaopin.txt", "a") as f:
for content in content_list:
f.write(json.dumps(content, ensure_ascii=False, indent=4))
f.write("\n")
def run(self): # 实现主要逻辑
# 1、获取url_list
url_list = self.get_url_list()
for url in url_list:
# 2、发送请求,获取响应
html_str = self.parse_url(url)
# 3、提取数据
content_list = self.get_content_list(html_str)
# 保存数据
self.save_content_list(content_list)
if __name__ == '__main__':
zhaopinSpider = ZhaopinSpider()
zhaopinSpider.run()
运行结果:
以第一条数据为例,在浏览器地址栏 输入 https://www.jobui.com/job/195859560/
果然跳转到了想要的页面,这也证明得到的数据没有错误。