python爬虫基础–使用正则提取51job内容输出到txt
from urllib import request
#url
url = 'https://search.51job.com/list/020000%252C010000%252C080200%252C070200%252C120300,000000,0000,00,9,99,%25E4%25BA%25BA%25E5%25B7%25A5%25E6%2599%25BA%25E8%2583%25BD,2,1.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=4&dibiaoid=0&address=&line=&specialarea=00&from=&welfare='
#变为请求
r=request.Request(url)
#访问得到结果
res = request.urlopen(r)
#读取并且解码
#print(res.read().decode('gbk'))#unicode解码方式
#读取网页编码格式
import chardet
html=res.read()
# code=chardet.detect(html)['encoding']
# print(code)
html=html.decode('gbk')
# print(html)
#提取
import re
#你需要留下的用(.*?),它的前后一定要有一个原来的存在内容,被你删掉的,用.*?表示
reg = re.compile('<div class="el">.*?<a target="_blank" title="(.*?)".*?<a target="_blank" title="(.*?)".*?<span class="t3">(.*?)</span>.*?<span class="t4">(.*?)</span>.*?<span class="t5">(.*?)</span>',re.S)
# 得到结果,是一个列表
data = re.findall(reg,html)
# 写入到 记事本
with open('51job.txt','w',encoding='utf-8') as file:
# 读取的每一个 each 都是 一个tuple
for each in data:
# 因为 file.write('只能是字符串')
for i in each:
# 再一次循环,一一写入
file.write(i+' ')
#每一条写完换个行
file.write('\n')