Home Backend Development Python Tutorial python2.7 implements crawler web page data

python2.7 implements crawler web page data

Jun 04, 2018 pm 05:57 PM
data Web page

This article mainly introduces python2.7 to implement crawler web page data in detail. It has certain reference value. Interested friends can refer to it.

I just learned Python recently and made a simple The crawler, as a simple demo, hopes to help beginners like me.

The code uses a crawler made with python2.7 to capture the job title, company name, salary, release time, etc. on 51job.

Go directly to the code. The comments in the code are relatively clear. If mysql is not installed, you need to block the relevant code:

#!/usr/bin/python 
# -*- coding: UTF-8 -*- 
 
from bs4 import BeautifulSoup 
import urllib 
import urllib2 
import codecs 
import re 
import time 
import logging 
import MySQLdb 
 
 
class Jobs(object): 
 
  # 初始化 
  """docstring for Jobs""" 
 
  def __init__(self): 
    super(Jobs, self).__init__() 
     
    logging.basicConfig(level=logging.DEBUG, 
         format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s') 
    #数据库的操作,没有mysql可以做屏蔽 
    self.db = MySQLdb.connect('127.0.0.1','root','rootroot','MySQL_Test',charset='utf8') 
    self.cursor = self.db.cursor() 
 
    #log日志的显示 
    self.logger = logging.getLogger("sjk") 
 
    self.logger.setLevel(level=logging.DEBUG) 
 
    formatter = logging.Formatter( 
      '%(asctime)s - %(name)s - %(levelname)s - %(message)s') 
    handler = logging.FileHandler('log.txt') 
    handler.setFormatter(formatter) 
    handler.setLevel(logging.DEBUG) 
    self.logger.addHandler(handler) 
 
    self.logger.info('初始化完成') 
 
  # 模拟请求数据 
  def jobshtml(self, key, page='1'): 
    try: 
      self.logger.info('开始请求第' + page + '页') 
      #网页url 
      searchurl = "https://search.51job.com/list/040000,000000,0000,00,9,99,{key},2,{page}.html?lang=c&stype=&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&providesalary=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare=" 
 
      user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:59.0) Gecko/20100101 Firefox/59.0' 
      #设置请求头 
      header = {'User-Agent': user_agent, 'Host': 'search.51job.com', 
           'Referer': 'https://www.51job.com/'} 
      #拼接url 
      finalUrl = searchurl.format(key=key, page=page) 
       
      request = urllib2.Request(finalUrl, headers=header) 
 
      response = urllib2.urlopen(request) 
      #等待网页加载完成 
      time.sleep(3) 
      #gbk格式解码 
      info = response.read().decode('gbk') 
 
      self.logger.info('请求网页网页') 
 
      self.decodeHtml(info=info, key=key, page=page) 
 
    except urllib2.HTTPError as e: 
      print e.reason 
 
  # 解析网页数据 
  def decodeHtml(self, info, key, page): 
    self.logger.info('开始解析网页数据') 
    #BeautifulSoup 解析网页 
    soup = BeautifulSoup(info, 'html.parser') 
    #找到class = t1 t2 t3 t4 t5 的标签数据 
    ps = soup.find_all(attrs={"class": re.compile(r'^t[1-5].*')}) 
    #打开txt文件 a+ 代表追加 
    f = codecs.open(key + '.txt', 'a+', 'UTF-8') 
    #清除之前的数据信息 
    f.truncate() 
 
    f.write('\n------------' + page + '--------------\n') 
 
    count = 1 
 
    arr = [] 
    #做一些字符串的处理,形成数据格式  iOS开发工程师 有限公司 深圳-南山区 0.9-1.6万/月 05-16 
    for pi in ps: 
      spe = " " 
      finalstr = pi.getText().strip() 
      arr.append(finalstr) 
      if count % 5 == 0: 
        #每一条数据插入数据库,如果没有安装mysql 可以将当前行注释掉 
        self.connectMySQL(arr=arr) 
        arr = [] 
        spe = "\n" 
      writestr = finalstr + spe 
      count += 1 
      f.write(writestr) 
    f.close() 
     
    self.logger.info('解析完成') 
 
#数据库操作 没有安装mysql 可以屏蔽掉 
  def connectMySQL(self,arr): 
    work=arr[0] 
    company=arr[1] 
    place=arr[2] 
    salary=arr[3] 
    time=arr[4] 
 
    query = "select * from Jobs_tab where \ 
    company_name='%s' and work_name='%s' and work_place='%s' \ 
    and salary='%s' and time='%s'" %(company,work,place,salary,time) 
    self.cursor.execute(query) 
 
    queryresult = self.cursor.fetchall() 
    #数据库中不存在就插入数据 存在就可以更新数据 不过我这边没有写 
    if len(queryresult) > 0: 
      sql = "insert into Jobs_tab(work_name,company_name,work_place,salary\ 
          ,time) values('%s','%s','%s','%s','%s')" %(work,company,place,salary,time) 
       
      try: 
        self.cursor.execute(sql) 
        self.db.commit() 
         
      except Exception as e: 
        self.logger.info('写入数据库失败') 
     
 
  #模拟登陆 
  # def login(self): 
  #   data = {'action':'save','isread':'on','loginname':'18086514327','password':'kui4131sjk'} 
 
 
  # 开始抓取 主函数 
  def run(self, key): 
 
    # 只要前5页的数据 key代表搜索工做类型 这边我是用的ios page是页数 
    for x in xrange(1, 6): 
      self.jobshtml(key=key, page=str(x)) 
 
    self.logger.info('写入数据库完成') 
 
    self.db.close() 
 
if __name__ == '__main__': 
 
  Jobs().run(key='iOS')
Copy after login

Catch the web page like this The data format is as follows:

Related recommendations:

Python implements crawler downloading pictures of beautiful women

Python implementation of crawler download comics example

The above is the detailed content of python2.7 implements crawler web page data. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to send web pages to desktop as shortcut in Edge browser? How to send web pages to desktop as shortcut in Edge browser? Mar 14, 2024 pm 05:22 PM

How to send web pages to the desktop as a shortcut in Edge browser? Many of our users want to display frequently used web pages on the desktop as shortcuts for the convenience of directly opening access pages, but they don’t know how to do it. In response to this problem, the editor of this issue will share the solution with the majority of users. , let’s take a look at the content shared in today’s software tutorial. The shortcut method of sending web pages to the desktop in Edge browser: 1. Open the software and click the "..." button on the page. 2. Select "Install this site as an application" in "Application" from the drop-down menu option. 3. Finally, click it in the pop-up window

Use ddrescue to recover data on Linux Use ddrescue to recover data on Linux Mar 20, 2024 pm 01:37 PM

DDREASE is a tool for recovering data from file or block devices such as hard drives, SSDs, RAM disks, CDs, DVDs and USB storage devices. It copies data from one block device to another, leaving corrupted data blocks behind and moving only good data blocks. ddreasue is a powerful recovery tool that is fully automated as it does not require any interference during recovery operations. Additionally, thanks to the ddasue map file, it can be stopped and resumed at any time. Other key features of DDREASE are as follows: It does not overwrite recovered data but fills the gaps in case of iterative recovery. However, it can be truncated if the tool is instructed to do so explicitly. Recover data from multiple files or blocks to a single

Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Open source! Beyond ZoeDepth! DepthFM: Fast and accurate monocular depth estimation! Apr 03, 2024 pm 12:04 PM

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

How to use Excel filter function with multiple conditions How to use Excel filter function with multiple conditions Feb 26, 2024 am 10:19 AM

If you need to know how to use filtering with multiple criteria in Excel, the following tutorial will guide you through the steps to ensure you can filter and sort your data effectively. Excel's filtering function is very powerful and can help you extract the information you need from large amounts of data. This function can filter data according to the conditions you set and display only the parts that meet the conditions, making data management more efficient. By using the filter function, you can quickly find target data, saving time in finding and organizing data. This function can not only be applied to simple data lists, but can also be filtered based on multiple conditions to help you locate the information you need more accurately. Overall, Excel’s filtering function is a very practical

What should I do if the images on the webpage cannot be loaded? 6 solutions What should I do if the images on the webpage cannot be loaded? 6 solutions Mar 15, 2024 am 10:30 AM

Some netizens found that when they opened the browser web page, the pictures on the web page could not be loaded for a long time. What happened? I checked that the network is normal, so where is the problem? The editor below will introduce to you six solutions to the problem that web page images cannot be loaded. Web page images cannot be loaded: 1. Internet speed problem The web page cannot display images. It may be because the computer's Internet speed is relatively slow and there are more softwares opened on the computer. And the images we access are relatively large, which may be due to loading timeout. As a result, the picture cannot be displayed. You can turn off the software that consumes more network speed. You can go to the task manager to check. 2. Too many visitors. If the webpage cannot display pictures, it may be because the webpages we visited were visited at the same time.

Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Google is ecstatic: JAX performance surpasses Pytorch and TensorFlow! It may become the fastest choice for GPU inference training Apr 01, 2024 pm 07:46 PM

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

Slow Cellular Data Internet Speeds on iPhone: Fixes Slow Cellular Data Internet Speeds on iPhone: Fixes May 03, 2024 pm 09:01 PM

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! Tesla robots work in factories, Musk: The degree of freedom of hands will reach 22 this year! May 06, 2024 pm 04:13 PM

The latest video of Tesla's robot Optimus is released, and it can already work in the factory. At normal speed, it sorts batteries (Tesla's 4680 batteries) like this: The official also released what it looks like at 20x speed - on a small "workstation", picking and picking and picking: This time it is released One of the highlights of the video is that Optimus completes this work in the factory, completely autonomously, without human intervention throughout the process. And from the perspective of Optimus, it can also pick up and place the crooked battery, focusing on automatic error correction: Regarding Optimus's hand, NVIDIA scientist Jim Fan gave a high evaluation: Optimus's hand is the world's five-fingered robot. One of the most dexterous. Its hands are not only tactile

See all articles